home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / Languages / MacHaskell 2.2 / progs / tutorial / tutorial.lhs < prev   
Encoding:
Text File  |  1994-09-27  |  80.3 KB  |  2,590 lines  |  [TEXT/ttxt]

  1. ag
  2. Page: 0    Introduction
  3.  
  4. This is a programming supplement to `A Gentle Introduction to Haskell'
  5. by Hudak and Fasel.  This supplement augments the tutorial by
  6. providing executable Haskell programs which you can run and
  7. experiment with.  All program fragments in the tutorial are
  8. found here, as well as other examples not included in the tutorial.
  9.  
  10. If you want to skip to the pages which cover Yale extensions to
  11. Haskell skip to page 27 of this tutorial using the Emacs command
  12. M-x ht-goto-page
  13.  
  14. You should have a copy of both the `Gentle Introduction' and the
  15. report itself to make full use of this tutorial.  Although the
  16. `Gentle Introduction' is meant to stand by itself, it is often easier
  17. to learn a language through actual use and experimentation than by
  18. reading alone.  Once you finish this introduction, we recommend that
  19. you proceed section by section through the `Gentle Introduction' and
  20. after having read each section go back to this online tutorial.  You
  21. should wait until you have finished the tutorial before attempting to
  22. read the report.  We assume that you are familiar with the basics of
  23. Emacs and that Haskell has been installed at your site.
  24.  
  25. This tutorial does not assume any familiarity with Haskell or other
  26. functional languages.  However, knowledge of almost-functional
  27. languages such as ML or Scheme is very useful.  Throughout the
  28. online component of this tutorial, we try to relate Haskell to
  29. other programming languages and clarify the written tutorial through
  30. additional examples and text.
  31.  
  32.  
  33. Organization of the Online Tutorial
  34.  
  35. This online tutorial is divided into a series of pages.  Each page
  36. covers one or more sections in the written tutorial.  You can use
  37. special Emacs commands to move back and forth through the pages of the
  38. online tutorial.  Each page is a single Haskell program.  Comments in
  39. the program contain the text of the online tutorial.  You can modify
  40. the program freely (this will not change the underlying tutorial
  41. file!) and ask the system to print the value of expressions defined in
  42. the program.
  43.  
  44. At the beginning of each page, the sections covered by the page are
  45. listed.  In addition, the start of each individual section is
  46. marked within each page.  Emacs commands can take you directly to a
  47. specific page or section in the tutorial.
  48.  
  49. To create useful, executable examples of Haskell code, some language
  50. constructs need to be revealed well before they are explained in the
  51. tutorial.  We attempt to point these out when they occur.  Some
  52. small changes have been made to the examples in the written tutorial;
  53. these are usually cosmetic and should be ignored.  Don't feel you have
  54. to understand everything on a page before you move on -- many times
  55. concepts become clearer as you move on and can relate them to other
  56. aspect of the language.
  57.  
  58. Each page of the tutorial defines a set of variables.  Some of
  59. these are named e1, e2, and so on.  These `e' variables are the ones
  60. which are meant for you to evaluate as you go through the tutorial.
  61. Of course you may evaluate any other expressions or variables you wish.
  62.  
  63.  
  64. The Haskell Report
  65.  
  66. While the report is not itself a tutorial on the Haskell language, it
  67. can be an invaluable reference to even a novice user.  A very
  68. important feature of Haskell is the prelude.  The prelude is a
  69. rather large chunk of Haskell code which is implicitly a part of every
  70. Haskell program.  Whenever you see functions used which are not
  71. defined in the current page, these come from the Prelude.  Appendix A
  72. of the report lists the entire Prelude; the index has an entry for
  73. every function in the Prelude.  Looking at the definitions in the
  74. Prelude is sometimes necessary to fully understand the programs in
  75. this tutorial.
  76.  
  77. Another reason to look at the report is to understand the syntax of
  78. Haskell.  Appendix B contains the complete syntax for Haskell.  The
  79. tutorial treats the syntax very informally; the precise details are
  80. found only in the report.
  81.  
  82.  
  83. The Yale Haskell System
  84.  
  85. This version of the tutorial runs under version Y2.1 of Yale Haskell.
  86. The Yale Haskell system is an interactive programming environment for
  87. the Haskell language.  The system is best used in conjunction with the
  88. Emacs editor.  Yale Haskell is available free of charge via ftp.
  89.  
  90.  
  91. Using the Compiler
  92.  
  93. Yale Haskell runs as a subprocess under Emacs.  While many commands
  94. are available to the Yale Haskell user, a single command is the
  95. primary means of communicating with the compiler: C-c e.  This command
  96. evaluates and prints an expression in the context of the program on
  97. the screen.  Here is what this command does:
  98.  
  99. a) You are prompted for an expression in the minibuffer.  You can
  100. use M-p or M-n to move through a ring of previous inputs.
  101.  
  102. b) If an inferior Haskell process is not running, a buffer named *haskell*
  103. is created and the Haskell compiler is started up.  The *haskell* buffer
  104. pops onto your screen.
  105.  
  106. c) If the program in the current page of the tutorial has not yet been
  107. compiled or the page has been modified after its most recent
  108. compilation, the entire page is compiled.  This may result in a short delay.
  109.  
  110. d) If there are no errors in the program, the expression entered in
  111. step a) is compiled in the context of the program.  Any value defined
  112. in the current page can be referenced.
  113.  
  114. e) If there are no errors in the expression, its value is printed in
  115. the *haskell* buffer.
  116.  
  117. There are also a few other commands you can use.  C-c i interrupts
  118. the Haskell program.  Some tight loops cannot be interrupted; in this
  119. case you will have to kill the Haskell process.    C-c q exits the Haskell
  120. process.
  121.  
  122.  
  123. Emacs Commands Used by the Tutorial
  124.  
  125. These commands are specific to the tutorial.  The tutorial is entered
  126. using M-x haskell-tutorial and is exited with C-c q.  To move among
  127. the pages of the tutorial, use
  128.  
  129. C-c C-f  -- go forward 1 page
  130. C-c C-b  -- go back 1 page
  131. M-x ht-goto-page    - goto a specific page of the tutorial
  132. M-x ht-goto-section - goto a specific section of the tutorial
  133.  
  134. Each page of the tutorial can be modified without changing the
  135. underlying text of the tutorial.  Changes are not saved as you go
  136. between pages.  To revert a page to its original form use C-c C-l.
  137.  
  138. You can get help regarding the Emacs commands with C-c ?.
  139.  
  140. Summary of Emacs commands used by the tutorial:
  141.   M-x haskell-tutorial  - start the tutorial
  142.   C-c C-f  - Go to the next page of the tutorial program
  143.   C-c C-b  - Go back to the previous page of the tutorial program
  144.   C-c C-l  - Restore the current page to its original form
  145.   C-c e    - Evaluate a Haskell expression
  146.   C-c i    - Interrupt a running Haskell program
  147.   C-c ?    - Shows a help message
  148.   M-x ht-goto-page    - goto a specific page of the tutorial
  149.   M-x ht-goto-section - goto a specific section of the tutorial
  150.  
  151.  
  152. You are now ready to start the tutorial.  Start by reading the `Gentle
  153. Introduction' section 1 then proceed through the online tutorial using
  154. C-c C-f to advance to the next page.  You should read about each topic
  155. first before turning to the associated programming example in the
  156. online tutorial.
  157.  
  158.  
  159. Page: 1   Section 2
  160.  
  161. Section: 2   Values, Types, and Other Goodies
  162.  
  163. This tutorial is written in `literate Haskell'.  This style requires
  164. that all lines containing Haskell code start with `>'; all other
  165. lines are comments and are discarded by the compiler.  Appendix C of
  166. the report defines the syntax of a literate program.  This is the
  167. first line of the Haskell program on this page:
  168.  
  169. > module Test(Bool) where
  170.  
  171. Comments at the end of source code lines start with `--'.  We use
  172. these throughout the tutorial to place explanatory text in the
  173. program. 
  174.  
  175. Remember to use C-c e to evaluate expressions, C-c ? for help.
  176.  
  177. All Haskell programs start with a module declaration, as in the
  178. previous `module Test(Bool) where'.  This can be ignored for now.
  179.  
  180. We will start by defining some identifiers (variables) using equations.
  181. You can print out the value of an identifier by typing C-c e and
  182. typing the name of the identifier you wish to evaluate.  This will
  183. compile the entire program, not just the line with the definition
  184. you want to see.  Not all definitions are very interesting to print out -
  185. by convention, we will use variables e1, e2, ... to denote values that
  186. are interesting to print.
  187.  
  188. We will start with some constants as well as their associated type.
  189. There are two ways to associate a type with a value: a type declaration
  190. and an expression type signature.  Here is an equation and a type
  191. declaration:
  192.  
  193. > e1 :: Int     -- This is a type declaration for the identifier e1
  194. > e1 = 5        -- This is an equation defining e1
  195.  
  196. You can evaluate the expression e1 and watch the system print `5'.
  197.  
  198. Remember that C-c e is prompting for an expression.  Expressions like
  199. e1 or 5 or 1+1 are all valid.  However, `e1 = 5' is a definition,
  200. not an expression.  Trying to evaluate it will result in a syntax error.
  201.  
  202. The type declaration for e1 is not really necessary but we will try to
  203. always provide type declarations for values to help document the program
  204. and to ensure that the system infers the same type we do for an expression.
  205. If you change the value for e1 to `True', the program will no longer
  206. compile due to the type mismatch.
  207.  
  208. We will briefly mention expression type signatures: these are attached to 
  209. expressions instead of identifiers.  Here are equivalent ways to do
  210. the previous definition:
  211.  
  212. > e2 = 5 :: Int
  213. > e3 = (2 :: Int) + (3 :: Int)
  214.  
  215. The :: has very low precedence in expressions and should usually be placed
  216. in parenthesis.
  217.  
  218. There are two completely separate languages in Haskell: an expression
  219. language for values and a type language for type signatures.  The type
  220. language is used only in the type declarations previously described and
  221. declarations of new types, described later.  Haskell uses a
  222. uniform syntax so that values resemble their type signature as much as
  223. possible.  However, you must always be aware of the difference between
  224. type expressions and value expressions.
  225.  
  226. Here are some of the predefined types Haskell provides:
  227.    type           Value Syntax                Type Syntax
  228. Small integers    <digits>                    Int
  229.  
  230. > e4 :: Int
  231. > e4 = 12345
  232.  
  233. Characters        '<character>'               Char
  234.  
  235. > e5 :: Char
  236. > e5 = 'a'
  237.  
  238. Strings           "chars"                     String
  239.  
  240. > e6 :: String
  241. > e6 = "abc"
  242.  
  243. Boolean           True, False                 Bool
  244.  
  245. > e7 :: Bool
  246. > e7 = True
  247.  
  248. Floating point    <digits.digits>             Float
  249.  
  250. > e8 :: Float
  251. > e8 = 123.456
  252.  
  253. Homogeneous list  [<exp1>,<exp2>,...]         [<constituant type>]
  254.  
  255. > e9 :: [Int]
  256. > e9 = [1,2,3]
  257.  
  258. Tuple             (<exp1>,<exp2>,...)         (<exp1-type>,<exp2-type>,...)
  259.  
  260. > e10 :: (Char,Int)
  261. > e10 = ('b',4)
  262.  
  263. Functional        described later             domain type -> range type
  264.  
  265. > succ :: Int -> Int  -- a function which takes an Int argument and returns Int
  266. > succ x = x + 1      -- test this by evaluating `succ 4'
  267.  
  268. Here's a few leftover examples from section 2:
  269.  
  270. > e11 = succ (succ 3)  -- you could also evaluate `succ (succ 3)' directly
  271. >                      -- by entering the entire expression to the C-c e
  272.  
  273. If you want to evaluate something more complex than the `e' variables
  274. defined here, it is better to enter a complex expression, such as
  275. succ (succ 3), directly than to edit a new definition like e10 into
  276. the program.  This is because any change to the program will require
  277. recompilation of the entire page.  The expressions entered to C-c e are
  278. compiled separately (and very quickly!).
  279.  
  280. Uncomment this next line to see a compile time type error.
  281.  
  282. > -- e12 = 'a'+'b'
  283.  
  284. Don't worry about the error message - it will make more sense later.
  285.  
  286. Proceed to the next page using C-c C-f
  287.  
  288. Page: 2   Section 2.1
  289.  
  290. Section: 2.1   Polymorphic Types
  291.  
  292. > module Test(Bool) where
  293.  
  294. The following line allows us to redefine functions in the standard
  295. prelude.  Ignore this for now.
  296.  
  297. > import Prelude hiding (length,head,tail,null)
  298.  
  299. Start with some sample lists to use in test cases:
  300.  
  301. > list1 :: [Int]
  302. > list1 = [1,2,3]
  303. > list2 :: [Char]         -- This is the really a String
  304. > list2 = ['a','b','c']   -- This is the same as "abc"; evaluate list2 and see.
  305. > list3 :: [[a]]          -- The element type of the inner list is unknown
  306. > list3 = [[],[],[],[]]   -- so this list can't be printed
  307. > list4 :: [Int]
  308. > list4 = 1:2:3:4:[]      -- Exactly the same as [1,2,3,4]; print it and see.
  309.  
  310. This is the length function.  You can test it by evaluating expressions
  311. such as `length list1'.  Function application is written by
  312. simple juxtaposition: `f(x)' in other languages would be `f x' in Haskell.
  313.  
  314. > length :: [a] -> Int
  315. > length [] = 0
  316. > length (x:xs) = 1 + length xs
  317.  
  318. Function application has the highest precedence, so 1 + length xs is
  319. parsed as 1 + (length xs).  In general, you have to surround
  320. non-atomic arguments to a function with parens.  This includes
  321. arguments which are also function applications.  For example,
  322. f g x is the function f applied to arguments g and x, similar to
  323. f(g,x) in other languages.  However, f (g x) is f applied to (g x), or
  324. f(g(x)), which means something quite different!  Be especially
  325. careful with infix operators: f x+1 y-2 would be parsed as (f x)+(1 y)-2.
  326. This is also true on the left of the `=': the parens around (x:xs) are
  327. absolutely necessary.  length x:xs would be parsed as (length x):xs.
  328.  
  329. Also be careful with prefix negation, -.  The application `f -1' is
  330. f-1, not f(-1).  Add parens around negative numbers to avoid this
  331. problem.
  332.  
  333. Here are some other list functions:
  334.  
  335. > head :: [a] -> a -- returns the first element in a list (same as car in lisp)
  336. > head (x:xs) = x
  337.  
  338. > tail :: [a] -> [a] -- removes the first element from a list (same as cdr)
  339. > tail (x:xs) = xs
  340.  
  341. > null :: [a] -> Bool
  342. > null [] = True
  343. > null (x:xs) = False
  344.  
  345. > cons :: a -> [a] -> [a]
  346. > cons x xs = x:xs
  347.  
  348. > nil :: [a]
  349. > nil = []
  350.  
  351. Length could be defined using these functions.  This is not good
  352. Haskell style but does illustrate these other list functions.
  353. Haskell programmers feel that the pattern matching style, as used in
  354. the previous version of length, is more natural and readable.
  355.  
  356. > length' :: [a] -> Int   -- Note that ' can be part of a name
  357. > length' x = if null x then 0 else 1 + length' (tail x)
  358.  
  359. A test case for length', cons, and nil
  360.  
  361. > e1 = length' (cons 1 (cons 2 nil))
  362.  
  363. We haven't said anything about errors yet.  Each of the following
  364. examples illustrates a potential runtime or compile time error.  The
  365. compile time error is commented out so that other examples will compile;
  366. you can uncomment them and see what happens.
  367.  
  368. > -- e2 = cons True False   -- Why is this not possible in Haskell?
  369. > e3 = tail (tail ['a'])  -- What happens if you evaluate this?
  370. > e4 = []       -- This is especially mysterious!
  371.  
  372. This last example, e4, is something hard to explain but is often
  373. encountered early by novices.  We haven't explained yet how the system
  374. prints out the expressions you type in - this will wait until later.
  375. However, the problem here is that e4 has the type [a].  The printer for
  376. the list datatype is complaining that it needs to know a specific type
  377. for the list elements even though the list has no elements!  This can
  378. be avoided by giving e4 a type such as [Int].  (To further confuse you,
  379. try giving e4 the type [Char] and see what happens.)
  380.  
  381. Page: 3   Section 2.2
  382.  
  383. Section: 2.2  User-Defined Types
  384.  
  385. > module Test(Bool) where
  386.  
  387. The type Bool is already defined in the Prelude so there is no
  388. need to define it here.
  389.  
  390. > data Color = Red | Green | Blue | Indigo | Violet deriving Text
  391.  
  392. The `deriving Text' is necessary if you want to print a Color value.
  393.  
  394. You can now evaluate these expressions.
  395.  
  396. > e1 :: Color
  397. > e1 = Red
  398. > e2 :: [Color]
  399. > e2 = [Red,Blue]
  400.  
  401. It is very important to keep the expression language and the type
  402. language in Haskell separated.  The data declaration above defines
  403. the type constructor Color.  This is a nullary constructor: it takes no
  404. arguments.  Color is found ONLY in the type language - it can not be
  405. part of an expression.  e1 = Color is meaningless.  (Actually, Color could
  406. be both a data constructor and a type constructor but we'll ignore this
  407. possibility for now).  On the other hand, Red, Blue, and so on are
  408. (nullary) data constructors.  They can appear in expressions and
  409. in patterns (described later).  The declaration e1 :: Blue would also
  410. be meaningless.  Data constructors can be defined ONLY in a data
  411. declaration.
  412.  
  413. In the next example, Point is a type constructor and Pt is a data
  414. constructor.  Point takes one argument and Pt takes two.  A data constructor
  415. like Pt is really just an ordinary function except that it can be used in
  416. a pattern.  Type signatures can not be supplied directly for data
  417. constructors; their typing is completely defined by the data declaration.
  418. However, data constructors have a signature just like any variable:
  419. Pt :: a -> a -> Point a   -- Not valid Haskell syntax
  420. That is, Pt is a function which takes two arguments with the same
  421. arbitrary type and returns a value containing the two argument values.
  422.  
  423. > data Point a = Pt a a   deriving Text
  424.  
  425. > e3 :: Point Float
  426. > e3 = Pt 2.0 3.0
  427. > e4 :: Point Char
  428. > e4 = Pt 'a' 'b'
  429. > e5 :: Point (Point Int)
  430. > e5 = Pt (Pt 1 2) (Pt 3 4)
  431. > -- e6 = Pt 'a' True         -- This is a typing error
  432.  
  433. The individual components of a point do not have names.
  434. Let's jump ahead a little so that we can write functions using these
  435. data types.  Data constructors (Red, Blue, ..., and Pt) can be used in
  436. patterns.  When more than one equation is used to define a function,
  437. pattern matching occurs top down.
  438.  
  439. A function to remove red from a list of colors.
  440.  
  441. > removeRed :: [Color] -> [Color]
  442. > removeRed [] = []
  443. > removeRed (Red:cs) = removeRed cs
  444. > removeRed (c:cs) = c : removeRed cs  -- c cannot be Red at this point
  445.  
  446. > e7 :: [Color]
  447. > e7 = removeRed [Blue,Red,Green,Red]
  448.  
  449. Pattern matching is capable of testing equality with a specific color.
  450.  
  451. All equations defining a function must share a common type.  A
  452. definition such as:
  453.  
  454. foo Red = 1
  455. foo (Pt x y) = x
  456.  
  457. would result in a type error since the argument to foo cannot be both a
  458. Color and a Point.  Similarly, the right hand sides must also share a
  459. common type; a definition such as
  460.  
  461. foo Red = Blue
  462. foo Blue = Pt Red Red
  463.  
  464. would also result in a type error.
  465.  
  466. Here are a couple of functions defined on points.
  467.  
  468. > dist :: Point Float -> Point Float -> Float
  469. > dist (Pt x1 y1) (Pt x2 y2) = sqrt ((x1-x2)^2 + (y1-y2)^2)
  470.  
  471. > midpoint :: Point Float -> Point Float -> Point Float
  472. > midpoint (Pt x1 y1) (Pt x2 y2) = Pt ((x1+x2)/2) ((y1+y2)/2)
  473.  
  474. > p1 :: Point Float
  475. > p1 = Pt 1.0 1.0
  476. > p2 :: Point Float
  477. > p2 = Pt 2.0 2.0
  478.  
  479. > e8 :: Float
  480. > e8 = dist p1 p2
  481. > e9 :: Point Float
  482. > e9 = midpoint p1 p2
  483.  
  484. The only way to take apart a point is to pattern match.
  485. That is, the two values which constitute a point must be extracted
  486. by matching a pattern containing the Pt data constructor.  Much
  487. more will be said about pattern matching later.
  488.  
  489. Haskell prints values in the same syntax used in expressions.  Thus
  490. Pt 1 2 would print as Pt 1 2 (of course, Pt 1 (1+1) would also print
  491. as Pt 1 2).
  492.  
  493. Page: 4  Section 2.3
  494.  
  495. Section: 2.3  Recursive Types
  496.  
  497. > module Test where
  498.  
  499. > data Tree a = Leaf a | Branch (Tree a) (Tree a)    deriving Text
  500.  
  501. The following typings are implied by this declaration.  As before,
  502. this is not valid Haskell syntax.
  503.  
  504. Leaf :: a -> Tree a
  505. Branch :: Tree a -> Tree a -> Tree a
  506.  
  507. > fringe :: Tree a -> [a]
  508. > fringe (Leaf x) = [x]
  509. > fringe (Branch left right) = fringe left ++ fringe right
  510.  
  511. The following trees can be used to test functions:
  512.  
  513. > tree1 :: Tree Int
  514. > tree1 = Branch (Leaf 1) (Branch (Branch (Leaf 2) (Leaf 3)) (Leaf 4))
  515. > tree2 :: Tree Int
  516. > tree2 = Branch (Branch (Leaf 3) (Leaf 1)) (Branch (Leaf 4) (Leaf 1))
  517. > tree3 :: Tree Int
  518. > tree3 = Branch tree1 tree2
  519.  
  520. Try evaluating `fringe tree1' and others.
  521.  
  522. Here's another tree function:
  523.  
  524. > twist :: Tree a -> Tree a
  525. > twist (Branch left right) = Branch right left
  526. > twist x = x        -- This equation only applies to leaves
  527.  
  528. Here's a function which compares two trees to see if they have the
  529. same shape.  Note the signature: the two trees need not contain the
  530. same type of values.
  531.  
  532. > sameShape :: Tree a -> Tree b -> Bool
  533. > sameShape (Leaf x) (Leaf y) = True
  534. > sameShape (Branch l1 r1) (Branch l2 r2) = sameShape l1 l2 && sameShape r1 r2
  535. > sameShape x y = False  -- One is a branch, the other is a leaf
  536.  
  537. The && function is a boolean AND function.
  538.  
  539. The entire pattern on the left hand side must match in order for the 
  540. right hand side to be evaluated.  The first clause requires both 
  541. arguments to be a leaf' otherwise the next equation is tested.  
  542. The last clause will always match: the final x and y match both 
  543. leaves and branches.
  544.  
  545. This compares a tree of integers to a tree of booleans.
  546.  
  547. > e1 = sameShape tree1 (Branch (Leaf True) (Leaf False))
  548.  
  549. Page: 5  Sections 2.4, 2.5, 2.6
  550.  
  551. Section: 2.4  Type Synonyms
  552.  
  553. > module Test(Bool) where
  554.  
  555. Since type synonyms are part of the type language only, it's hard to
  556. write a program which shows what they do.  Essentially, they are like
  557. macros for the type language.  They can be used interchangeably with their
  558. definition:
  559.  
  560. > e1 :: String
  561. > e1 = "abc"
  562. > e2 :: [Char]   -- No different than String
  563. > e2 = e1
  564.  
  565. In the written tutorial the declaration of `Addr' is a data type
  566. declaration, not a synonym declaration.  This shows that the data
  567. type declaration as well as a signature can reference a synonym.
  568.  
  569. Section: 2.5  Built-in Types
  570.  
  571. Tuples are an easy way of grouping a set of data values.  Here are
  572. a few tuples.  Note the consistancy in notation between the values and
  573. types.
  574.  
  575. > e3 :: (Bool,Int)
  576. > e3 = (True,4)
  577. > e4 :: (Char,[Int],Char)
  578. > e4 = ('a',[1,2,3],'b')
  579.  
  580. Here's a function which returns the second component of a 3 tuple.
  581.  
  582. > second :: (a,b,c) -> b
  583. > second (a,b,c) = b
  584.  
  585. Try out `second e3' and `second e4' - what happens?
  586.  
  587. Each different size of tuple is a completely distinct type.  There is
  588. no general way to append two arbitrary tuples or randomly select the
  589. i'th component of an arbitrary tuple.  Here's a function built using
  590. 2-tuples to represent intervals.
  591.  
  592. Use a type synonym to represent homogeneous 2 tuples
  593.  
  594. > type Interval a = (a,a)
  595.  
  596. > containsInterval :: Interval Int -> Interval Int -> Bool
  597. > containsInterval (xmin,xmax) (ymin,ymax) = xmin <= ymin && xmax >= ymax
  598.  
  599. > p1 :: Interval Int
  600. > p1 = (2,3)
  601. > p2 :: Interval Int
  602. > p2 = (1,4)
  603.  
  604. > e5 = containsInterval p1 p2
  605. > e6 = containsInterval p2 p1
  606.  
  607. Here's a type declaration for a type isomorphic to lists:
  608.  
  609. > data List a = Nil | Cons a (List a) deriving Text
  610.  
  611. Except for the notation, this is completely equivalent to ordinary lists
  612. in Haskell.
  613.  
  614. > length' :: List a -> Int
  615. > length' Nil = 0
  616. > length' (Cons x y) = 1 + length' y
  617.  
  618. > e7 = length' (Cons 'a' (Cons 'b' (Cons 'c' Nil)))
  619.  
  620. It is hard to demonstrate much about the `non-specialness' of built-in
  621. types.  However, here is a brief summary:
  622.  
  623. Numbers and characters, such as 1, 2.2, or 'a', are the same as nullary
  624. type constructors.
  625.  
  626. Lists have a special type constructor, [a] instead of List a, and
  627. an odd looking data constructor, [].  The other data constructor, :, is
  628. not `unusual', syntactically speaking.  The notation [x,y] is just
  629. syntax for x:y:[] and "abc" for 'a' : 'b' : 'c' : [].
  630.  
  631. Tuples use a special syntax.  In a type expression, a 2 tuple containing
  632. types a and be would be written (a,b) instead of using a prefix type
  633. constructor such as Tuple2 a b.  This same notation is used to build
  634. tuple values: (1,2) would construct a 2 tuple containing the values 1 and 2.
  635.  
  636.  
  637. Page: 6   Sections 2.5.1, 2.5.2
  638.  
  639. > module Test(Bool) where
  640.  
  641. Section: 2.5.1  List Comprehensions and Arithmetic Sequences
  642.  
  643. Warning: brackets in Haskell are used in three different sorts
  644. of expressions: lists, as in [a,b,c], sequences (distinguished by
  645. the ..), as in [1..2], and list comprehensions (distinguished by the
  646. bar: |), as in [x+1 | x <- xs, x > 1].
  647.  
  648. Before list comprehensions, consider sequences:
  649.  
  650. > e1 :: [Int]
  651. > e1 = [1..10]   -- Step is 1
  652. > e2 :: [Int]
  653. > e2 = [1,3..10] -- Step is 3 - 1
  654. > e3 :: [Int]
  655. > e3 = [1,-1..-10]
  656. > e4 :: [Char]
  657. > e4 = ['a'..'z']   -- This works on chars too
  658.  
  659. We'll avoid infinite sequences like [1..] for now.  If you print one,
  660. use C-c i to interrupt the Haskell program.
  661.  
  662. List comprehensions are very similar to nested loops.  They return a
  663. list of values generated by the expression inside the loop.  The filter
  664. expressions are similar to conditionals in the loop.
  665.  
  666. This function does nothing at all!  It just scans through a list and
  667. copies it into a new one.
  668.  
  669. > doNothing :: [a] -> [a]
  670. > doNothing l = [x | x <- l]
  671.  
  672. Adding a filter to the previous function allows only selected elements to
  673. be generated.  This is similar to what is done in quicksort.
  674.  
  675. > positives :: [Int] -> [Int]
  676. > positives l = [x | x <- l, x > 0]
  677.  
  678. > e5 = positives [2,-4,5,6,-5,3]
  679.  
  680. Now the full quicksort function.
  681.  
  682. > quicksort :: [Char] -> [Char]  -- Use Char just to be different!
  683. > quicksort [] = []
  684. > quicksort (x:xs) = quicksort [y | y <- xs, y <= x] ++
  685. >                    [x] ++
  686. >                    quicksort [y | y <- xs, y > x]
  687.  
  688. > e6 = quicksort "Why use Haskell?"
  689.  
  690. Now for some nested loops.  Each generator, <-, adds another level of
  691. nesting to the loop.  The variable introduced by each generator
  692. can be used in each following generator; all variables can be used in the
  693. generated expression:
  694.  
  695. > e7 :: [(Int,Int)]
  696. > e7 = [(x,y) | x <- [1..5], y <- [x..5]]
  697.  
  698. Now add some guards: (the /= function is `not equal')
  699.  
  700. > e8 :: [(Int,Int)]
  701. > e8 = [(x,y) | x <- [1..7], x /= 5, y <- [x..8] , x*y /= 12]
  702.  
  703. This is the same as the loop: (going to a psuedo Algol notation)
  704. for x := 1 to 7 do
  705.  if x <> 5 then
  706.   for y := x to 8 do
  707.    if x*y <> 12
  708.     generate (x,y)
  709.  
  710. Section: 2.5.2  Strings
  711.  
  712. > e9 = "hello" ++ " world"
  713.  
  714. Page: 7    Sections 3, 3.1
  715.  
  716. > module Test(Bool) where
  717. > import Prelude hiding (map)
  718.  
  719. Section: 3   Functions
  720.  
  721. > add :: Int -> Int -> Int
  722. > add x y = x+y
  723.  
  724. > e1 :: Int
  725. > e1 = add 1 2
  726.  
  727. This Int -> Int is the latter part of the signature of add:
  728.  
  729. add :: Int -> (Int -> Int)
  730.  
  731. > succ :: Int -> Int
  732. > succ = add 1
  733.  
  734. > e2 :: Int
  735. > e2 = succ 3
  736.  
  737. > map :: (a->b) -> [a] -> [b]
  738. > map f [] = []
  739. > map f (x:xs) = f x : (map f xs)
  740.  
  741. > e3 :: [Int]
  742. > e3 = map (add 1) [1,2,3]
  743.  
  744. This next definition is the equivalent to e3
  745.  
  746. > e4 :: [Int]
  747. > e4 = map succ [1,2,3]
  748.  
  749. Heres a more complex example.  Define flist to be a list of functions:
  750.  
  751. > flist :: [Int -> Int]
  752. > flist = map add [1,2,3]
  753.  
  754. This returns a list of functions which add 1, 2, or 3 to their input.
  755. Haskell should print flist as something like
  756.  [<<function>>,<<function>>,<<function>>]
  757.  
  758. Now, define a function which takes a function and returns its value
  759. when applied to the constant 1:
  760.  
  761. > applyTo1 :: (Int -> a) -> a
  762. > applyTo1 f = f 1
  763.  
  764. > e5 :: [Int]
  765. > e5 = map applyTo1 flist  -- Apply each function in flist to 1
  766.  
  767. If you want to look at how the type inference works, figure out how
  768. the signatures of map, applyTo1, and flist combine to yield [Int].
  769.  
  770. Section: 3.1  Lambda Abstractions
  771.  
  772. The symbol \ is like `lambda' in lisp or scheme.
  773.  
  774. Anonymous functions are written as \ arg1 arg2 ... argn -> body
  775. Instead of naming every function, you can code it inline with this
  776. notation:
  777.  
  778. > e6 = map (\f -> f 1) flist
  779.  
  780. Be careful with the syntax here.  \x->\y->x+y parses as
  781.  \ x ->\ y -> x + y.  The ->\ is all one token.  Use spaces!!
  782.  
  783. This is identical to e5 except that the applyTo1 function has no name.
  784.  
  785. Function arguments on the left of an = are the same as lambda on the
  786. right:
  787.  
  788. > add' = \x y -> x+y    -- identical to add
  789. > succ' = \x -> x+1     -- identical to succ
  790.  
  791. As with ordinary function, the parameters to anonymous functions
  792. can be patterns:
  793.  
  794. > e7 :: [Int]
  795. > e7 = map (\(x,y) -> x+y) [(1,2),(3,4),(5,6)]
  796.  
  797. Functions defined by more than one equation, like map, cannot
  798. be converted to anonymous lambda functions quite as easily - a case
  799. statement is also required.  This is discussed later.
  800.  
  801. Page: 8   Sections 3.2, 3.2.1, 3.2.2
  802.  
  803. > module Test(Bool) where
  804.  
  805. > import Prelude hiding ((++),(.))
  806.  
  807. Section: 3.2  Infix operators
  808.  
  809. Haskell has both identifiers, like `x', and operators, like `+'.
  810. These are just two different types of syntax for variables.
  811. However, operators are by default used in infix notation.
  812.  
  813. Briefly, identifiers begin with a letter and may have numbers, _, and '
  814. in them:  x, xyz123, x'', xYz'_12a.  The case of the first letter
  815. distinguishes variables from data constructors (or type variables from
  816. type constructors).  An operator is a string of symbols, where
  817. :!#$%&*+./<=>?@\^| are all symbols.  If the first character is : then
  818. the operator is a data constructor; otherwise it is an ordinary
  819. variable operator.  The - and ~ characters may start a symbol but cannot
  820. be used after the first character.  This allows a*-b to parse as
  821. a * - b instead of a *- b.
  822.  
  823. Operators can be converted to identifiers by enclosing them in parens.
  824. This is required in signature declarations.  Operators can be defined
  825. as well as used in the infix style:
  826.  
  827. > (++) :: [a] -> [a] -> [a]
  828. > [] ++ y = y
  829. > (x:xs) ++ y = x : (xs ++ y)
  830.  
  831. Table 2 (Page 54) of the report is invaluable for sorting out the
  832. precedences of the many predefined infix operators.
  833.  
  834. > e1 = "Foo" ++ "Bar"
  835.  
  836. This is the same function without operator syntax
  837.  
  838. > appendList :: [a] -> [a] -> [a]
  839. > appendList [] y = y
  840. > appendList (x:xs) y = x : appendList xs y
  841.  
  842. > (.) :: (b -> c) -> (a -> b) -> (a -> c)
  843. > f . g = \x -> f (g x)
  844.  
  845. > add1 :: Int -> Int
  846. > add1 x = x+1
  847.  
  848. > e2 = (add1 . add1) 3
  849.  
  850. Section: 3.2.1  Sections
  851.  
  852. Sections are a way of creating unary functions from infix binary
  853. functions.  When a parenthesized expression starts or ends in an
  854. operator, it is a section.  Another definition of add1:
  855.  
  856. > add1' :: Int -> Int
  857. > add1' = (+ 1)
  858.  
  859. > e3 = add1' 4
  860.  
  861. Here are a few section examples:
  862.  
  863. > e4 = map (++ "abc") ["x","y","z"]
  864.  
  865. > e5 = map ("abc" ++) ["x","y","z"]
  866.  
  867.  
  868. Section: 3.2.2  Fixity Declarations
  869.  
  870. We'll avoid any demonstration of fixity declarations.  The Prelude
  871. contains numerous examples.
  872.  
  873. Page: 9  Sections 3.3, 3.4, 3.5
  874.  
  875. > module Test(Bool) where
  876.  
  877. > import Prelude hiding (take,zip)
  878.  
  879. Section: 3.3  Functions are Non-strict
  880.  
  881. Observing lazy evaluation can present difficulties.  The essential
  882. question is `does an expression get evaluated?'.  While in theory using a
  883. non-terminating computation is the way evaluation issues are examined,
  884. we need a more practical approach.  In expressions, Haskell uses `_'
  885. to denote bottom.  Evaluation of `_' will halt execution and print an
  886. informative error message giving the location of the _ which was
  887. evaluated.  While it would seem that `_' is of little use to the
  888. ordinary programmer, this construct is actually quite handy.  Bottom
  889. can be used to create stub functions for program components which have
  890. not been written yet or as a value to insert into data structures
  891. where a data value is required but should never be used.
  892.  
  893. > e1 :: Bool    -- This can be any type at all!
  894. > e1 = _        -- evaluate this and see what happens.
  895.  
  896. > const1 :: a -> Int
  897. > const1 x = 1
  898.  
  899. > e2 :: Int
  900. > e2 = const1 _  -- The bottom is not needed and will thus not be evaluated.
  901.  
  902. Section: 3.4  "Infinite" Data Structures
  903.  
  904. Data structures are constructed lazily.  A constructor like : will not
  905. evaluate its arguments until they are demanded.  All demands arise from
  906. the need to print the result of the computation -- components not needed
  907. to compute the printed result will not be evaluated.
  908.  
  909. > list1 :: [Int]
  910. > list1 = (1:_)
  911.  
  912. > e3 = head list1    -- does not evaluate _
  913. > e4 = tail list1    -- does evaluate _
  914.  
  915. Some infinite data structures.  Don't print these!  If you do, you will
  916. need to interrupt the system (C-c i) or kill the Haskell process.
  917.  
  918. > ones :: [Int]
  919. > ones = 1 : ones
  920.  
  921. > numsFrom :: Int -> [Int]
  922. > numsFrom n = n : numsFrom (n+1)
  923.  
  924. An alternate numsFrom using series notation:
  925.  
  926. > numsFrom' :: Int -> [Int]
  927. > numsFrom' n = [n..]
  928.  
  929. > squares :: [Int]
  930. > squares = map (^2) (numsFrom 0)
  931.  
  932. Before we start printing anything, we need a function to truncate these
  933. infinite lists down to a more manageable size.  The `take' function
  934. extracts the first k elements of a list:
  935.  
  936. > take :: Int -> [a] -> [a]
  937. > take 0 x      = []                 -- two base cases: k = 0
  938. > take k []     = []                 -- or the list is empty
  939. > take k (x:xs) = x : take (k-1) xs
  940.  
  941. now some printable lists:
  942.  
  943. > e5 :: [Int]
  944. > e5 = take 5 ones
  945.  
  946. > e6 :: [Int]
  947. > e6 = take 5 (numsFrom 10)
  948.  
  949. > e7 :: [Int]
  950. > e7 = take 5 (numsFrom' 0)
  951.  
  952. > e8 :: [Int]
  953. > e8 = take 5 squares
  954.  
  955. zip is a function which turns two lists into a list of 2 tuples.  If
  956. the lists are of differing sizes, the result is as long as the
  957. shortest list.
  958.  
  959. > zip (x:xs) (y:ys) = (x,y) : zip xs ys
  960. > zip xs ys = []   -- one of the lists is []
  961.  
  962. > e9 :: [(Int,Int)]
  963. > e9 = zip [1,2,3] [4,5,6]
  964.  
  965. > e10 :: [(Int,Int)]
  966. > e10 = zip [1,2,3] ones
  967.  
  968. > fib :: [Int]
  969. > fib = 1 : 1 : [x+y | (x,y) <- zip fib (tail fib)]
  970.  
  971. > e11 = take 5 fib
  972.  
  973. This can be done without the list comprehension:
  974.  
  975. > fib' :: [Int]
  976. > fib' = 1 : 1 : map (\(x,y) -> x+y) (zip fib (tail fib))
  977.  
  978. This could be written even more cleanly using a map function which
  979. maps a binary function over two lists at once.  This is in the
  980. Prelude and is called zipWith (the name map2 would possibly be clearer!).
  981.  
  982. > fib'' :: [Int]
  983. > fib'' = 1 : 1 : zipWith (+) fib (tail fib)
  984.  
  985. For more examples using infinite structures look in the demo files
  986. that come with Yale Haskell.  Both the pascal program and the
  987. primes program use infinite lists.
  988.  
  989. Section: 3.5  The Error Function
  990.  
  991. Too late - we already used it!  One thing to note is that `_' is not
  992. part of Haskell 1.2 but will be a part of Haskell 1.3 when it is
  993. ready.  Meanwhile, we have added _ to the Yale system in anticipation
  994. of the new report.
  995.  
  996.  
  997. Page: 10   Sections 4, 4.1, 4.2
  998.  
  999. > module Test(Bool) where
  1000.  
  1001. > import Prelude hiding (take,(^))
  1002.  
  1003. Section: 4  Case Expressions and Pattern Matching
  1004.  
  1005. Now for details of pattern matching.  We use [Int] instead of [a]
  1006. since the only value of type [a] is [].
  1007.  
  1008. > contrived :: ([Int], Char, (Int, Float), String, Bool) -> Bool
  1009. > contrived ([], 'b', (1, 2.0), "hi", True) = False
  1010. > contrived x = True   -- add a second equation to avoid runtime errors
  1011.  
  1012. > e1 :: Bool
  1013. > e1 = contrived ([], 'b', (1, 2.0), "hi", True)
  1014. > e2 :: Bool
  1015. > e2 = contrived ([1], 'b', (1, 2.0), "hi", True)
  1016.  
  1017. Contrived just tests its input against a big constant.
  1018.  
  1019. Linearity in pattern matching implies that patterns can only compare
  1020. values with constants.  The following is not valid Haskell:
  1021.  
  1022. member x [] = False
  1023. member x (x:ys) = True      -- Invalid since x appears twice
  1024. member x (y:ys) = member x ys
  1025.  
  1026. The use of `_' in patterns differs from the use of `_' in an
  1027. expression.  In either case `_' can be thought of as a "don't care"
  1028. object; in an expression it means that you don't care what the value
  1029. of the expression is since you never intend to use it.  In a pattern,
  1030. it means that you don't care what value the `_' is being matched
  1031. against.
  1032.  
  1033. > f :: [a] -> [a]
  1034. > f s@(x:xs) = x:s
  1035. > f _ = []
  1036.  
  1037. > e3 = f "abc"
  1038.  
  1039. Another use of _:
  1040.  
  1041. > middle :: (a,b,c) -> b
  1042. > middle (_,x,_) = x
  1043.  
  1044. > e4 :: Char
  1045. > e4 = middle (True, 'a', "123")
  1046.  
  1047. > (^) :: Int -> Int -> Int
  1048. > x ^ 0 = 1
  1049. > x ^ (n+1) = x*(x^n)
  1050.  
  1051. > e5 :: Int
  1052. > e5 = 3^3
  1053. > e6 :: Int
  1054. > e6 = 4^(-2)  -- Notice the behavior of the + pattern on this one
  1055.  
  1056. Section: 4.1  Pattern Matching Semantics
  1057.  
  1058. Here's an extended example to illustrate the left -> right, top -> bottom
  1059. semantics of pattern matching.
  1060.  
  1061. > foo :: (Int,[Int],Int) -> Int
  1062. > foo (1,[2],3)   = 1
  1063. > foo (2,(3:_),3) = 2
  1064. > foo (1,_,3)     = 3
  1065. > foo _           = 4
  1066.  
  1067. > e7 = foo (1,[],3)
  1068. > e8 = foo (1,_,3)
  1069. > e9 = foo (1,1:_,3)
  1070. > e10 = foo (2,_,2)
  1071. > e11 = foo (3,_,_)
  1072.  
  1073. Now add some guards:
  1074.  
  1075. > sign :: Int -> Int
  1076. > sign x | x > 0  = 1
  1077. >        | x == 0 = 0
  1078. >        | x < 0  = -1
  1079.  
  1080. > e12 = sign 3
  1081.  
  1082. The last guard is often `True' to catch all other cases.  The identifier
  1083. `otherwise' is defined as True for use in guards:
  1084.  
  1085. > max' :: Int -> Int -> Int
  1086. > max' x y | x > y      = x
  1087. >          | otherwise  = y
  1088.  
  1089. Guards can refer to any variables bound by pattern matching.  When
  1090. no guard is true, pattern matching resumes at the next equation.  Guards
  1091. may also refer to values bound in an associated where declaration.
  1092.  
  1093.  
  1094. > inOrder :: [Int] -> Bool
  1095. > inOrder (x1:x2:xs) | x1 <= x2 = True
  1096. > inOrder _                     = False
  1097.  
  1098. > e13 = inOrder [1,2,3]
  1099. > e14 = inOrder [2,1]
  1100.  
  1101. Section: 4.2  An Example
  1102.  
  1103. > take :: Int -> [a] -> [a]
  1104. > take 0     _      = []
  1105. > take _     []     = []
  1106. > take (n+1) (x:xs) = x:take n xs
  1107.  
  1108. > take' :: Int -> [a] -> [a]
  1109. > take' _     []     = []
  1110. > take' 0     _      = []
  1111. > take' (n+1) (x:xs) = x:take' n xs
  1112.  
  1113. > e15, e16, e17, e18 :: [Int]
  1114. > e15 = take 0 _
  1115. > e16 = take' 0 _
  1116. > e17 = take _ []
  1117. > e18 = take' _ []
  1118.  
  1119. Page: 11    Sections 4.3, 4.4, 4.5, 4.6
  1120.  
  1121. > module Test(Bool) where
  1122.  
  1123. > import Prelude hiding (take)
  1124.  
  1125. Section: 4.3 Case Expressions
  1126.  
  1127. The function `take' using a case statement instead of multiple equations:
  1128.  
  1129. > take :: Int -> [a] -> [a]
  1130. > take m ys = case (m,ys) of
  1131. >              (0  ,_)    -> []
  1132. >              (_  ,[])   -> []
  1133. >              (n+1,x:xs) -> x : take n xs
  1134.  
  1135. The function take using if then else.  We can also eliminate the n+k
  1136. pattern just for fun.  The original version of take is much easier to read!
  1137.  
  1138. > take' :: Int -> [a] -> [a]
  1139. > take' m ys = if m == 0 then [] else
  1140. >               if null ys then [] else
  1141. >                if m > 0 then head ys : take (m-1) (tail ys)
  1142. >                 else error "m < 0"
  1143.  
  1144. Section: 4.4  Lazy Patterns
  1145.  
  1146. Before the client-server example, here is a contrived example of lazy
  1147. patterns.  The first version will fail to pattern match whenever the
  1148. the first argument is [].  The second version will always pattern
  1149. match initially but x will fail if used when the list is [].
  1150.  
  1151. > nonlazy :: [Int] -> Bool -> [Int]
  1152. > nonlazy (x:xs) isNull  = if isNull then [] else [x]
  1153.  
  1154. > e1 = nonlazy [1,2] False
  1155. > e2 = nonlazy [] True
  1156. > e3 = nonlazy [] False
  1157.  
  1158. This version will never fail the initial pattern match
  1159.  
  1160. > lazy :: [Int] -> Bool -> [Int]
  1161. > lazy ~(x:xs) isNull  = if isNull then [] else [x]
  1162.  
  1163. > e4 = lazy [1,2] False
  1164. > e5 = lazy [] True
  1165. > e6 = lazy [] False
  1166.  
  1167. The server - client example is a little hard to demonstrate.  We'll avoid
  1168. the initial version which loops.  Here is the version with irrefutable
  1169. patterns.
  1170.  
  1171. > type Response = Int
  1172. > type Request = Int
  1173.  
  1174. > client :: Request -> [Response] -> [Request]
  1175. > client init ~(resp:resps) = init : client (next resp) resps
  1176.  
  1177. > server :: [Request] -> [Response]
  1178. > server (req : reqs) = process req : server reqs
  1179.  
  1180. Next maps the response from the previous request onto the next request
  1181.  
  1182. > next :: Response -> Request 
  1183. > next resp = resp
  1184.  
  1185. Process maps a request to a response
  1186.  
  1187. > process :: Request -> Response
  1188. > process req = req+1
  1189.  
  1190. > requests :: [Request]
  1191. > requests = client 0 responses
  1192.  
  1193. > responses :: [Response]
  1194. > responses = server requests
  1195.  
  1196. > e7 = take 5 responses
  1197.  
  1198. The lists of requests and responses are infinite - there is no need to
  1199. check for [] in this program.  These lists correspond to streams in other
  1200. languages.
  1201.  
  1202. Here is fib again:
  1203.  
  1204. > fib :: [Int]
  1205. > fib@(_:tfib) = 1 : 1 : [ a+b | (a,b) <- zip fib tfib]
  1206.  
  1207. > e8 = take 10 fib
  1208.  
  1209. Section: 4.5  Lexical Scoping and Nested Forms
  1210.  
  1211. One thing that is important to note is that the order of the
  1212. definitions in a program, let expression, or where clauses is
  1213. completely arbitrary.  Definitions can be arranged 'top down'
  1214. or `bottom up' without changing the program.
  1215.  
  1216. > e9 = let y = 2 :: Float
  1217. >          f x = (x+y)/y
  1218. >      in f 1 + f 2
  1219.  
  1220. > f :: Int -> Int -> String
  1221. > f x y | y > z  = "y > x^2"
  1222. >       | y == z = "y = x^2"
  1223. >       | y < z  = "y < x^2"
  1224. >   where
  1225. >     z = x*x
  1226.  
  1227. > e10 = f 2 5
  1228. > e11 = f 2 4
  1229.  
  1230. Section: 4.6  Layout
  1231.  
  1232. There's nothing much to demonstrate here.  We have been using layout all
  1233. through the tutorial.  The main thing is to be careful line up the
  1234. first character of each definition.  For example, if you
  1235. change the indentation of the definition of f in e9 you will get a
  1236. parse error.
  1237.  
  1238. Page: 12  Section 5
  1239.  
  1240. > module Test(Bool) where
  1241.  
  1242. > import Prelude hiding (elem)
  1243.  
  1244. Section: 5  Type Classes
  1245.  
  1246. Names in the basic class structure of Haskell cannot be hidden (they are
  1247. in PreludeCore) so we have to modify the names used in the tutorial.
  1248.  
  1249. Here is a new Eq class:
  1250.  
  1251. > class Eq' a where
  1252. >   eq :: a -> a -> Bool
  1253.  
  1254. Now we can define elem using eq from above:
  1255.  
  1256. > elem :: (Eq' a) => a -> [a] -> Bool
  1257. > x `elem` [] = False
  1258. > x `elem` (y:ys) = x `eq` y || x `elem` ys
  1259.  
  1260. Before this is of any use, we need to admit some types to Eq'
  1261.  
  1262. > instance Eq' Int where
  1263. >  x `eq` y = abs (x-y) < 3  -- Let's make this `nearly equal' just for fun
  1264.  
  1265. > instance Eq' Float where
  1266. >  x `eq` y = abs (x-y) < 0.1
  1267.  
  1268. > list1 :: [Int]
  1269. > list1 = [1,5,9,23]
  1270.  
  1271. > list2 :: [Float]
  1272. > list2 = [0.2,5.6,33,12.34]
  1273.  
  1274. > e1 = 2 `elem` list1
  1275. > e2 = 100 `elem` list1
  1276. > e3 = 0.22 `elem` list2
  1277.  
  1278. Watch out!  Integers in Haskell are overloaded - without a type signature
  1279. to designate an integer as an Int, expressions like 3 `eq` 3 will be
  1280. ambiguous.  See 5.5.4 about this problem.
  1281.  
  1282. Now to add the tree type:
  1283.  
  1284. > data Tree a = Leaf a | Branch (Tree a) (Tree a)   deriving Text
  1285.  
  1286. > instance (Eq' a) => Eq' (Tree a) where
  1287. >   (Leaf a)       `eq` (Leaf b)       = a `eq` b
  1288. >   (Branch l1 r1) `eq` (Branch l2 r2) =  (l1 `eq` l2) && (r1 `eq` r2)
  1289. >   _              `eq` _              = False
  1290.  
  1291. > tree1,tree2 :: Tree Int
  1292. > tree1 = Branch (Leaf 1) (Leaf 2)
  1293. > tree2 = Branch (Leaf 2) (Leaf 1)
  1294.  
  1295. > e4 = tree1 `eq` tree2
  1296.  
  1297. Now make a new class with Eq' as a super class:
  1298.  
  1299. > class (Eq' a) => Ord' a where
  1300. >  lt,le :: a -> a -> Bool          -- lt and le are operators in Ord'
  1301. >  x `le` y = x `eq` y || x `lt` y  -- This is a default for le
  1302.  
  1303. The typing of lt & le is 
  1304.  
  1305.  le,lt :: (Ord' a) => a -> a -> Bool
  1306.  
  1307. This is identical to
  1308.  
  1309.  le,lt :: (Eq' a,Ord' a) => a -> a -> Bool
  1310.  
  1311. Make Int an instance of Ord:
  1312.  
  1313. > instance Ord' Int where
  1314. >  x `lt` y = x < y+1
  1315.  
  1316. > i :: Int  -- Avoid ambiguity
  1317. > i = 3
  1318. > e5 :: Bool
  1319. > e5 = i `lt` i
  1320.  
  1321. Some constraints on instance declarations:
  1322.   A program can never have more than one instance declaration for
  1323.     a given combination of data type and class.
  1324.   If a type is declared to be a member of a class, it must also be
  1325.     declared in all superclasses of that class.
  1326.   An instance declaration does not need to supply a method for every
  1327.     operator in the class.  When a method is not supplied in an
  1328.     instance declaration and no default is present in the class
  1329.     declaration, a runtime error occurs if the method is invoked.
  1330.   You must supply the correct context for an instance declaration --
  1331.     this context is not inferred automatically.
  1332.  
  1333. Section: 5.1  Equality and Ordered Classes
  1334. Section: 5.2  Enumeration and Index Classes
  1335.  
  1336. No examples are provided for 5.1 or 5.2.  The standard Prelude contains
  1337. many instance declarations which illustrate the Eq, Ord, and Enum classes.
  1338.  
  1339. Page: 13    Section 5.3
  1340.  
  1341. > module Test(Bool) where
  1342.  
  1343. Section: 5.3   The Text Class
  1344.  
  1345. This is the slow showTree.  The `show' function is part of the
  1346. Text class and works with all the built-in types.  The context `Text a'
  1347. arises from the call to show for leaf values.
  1348.  
  1349. > data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Text
  1350.  
  1351. > showTree :: (Text a) => Tree a -> String
  1352. > showTree (Leaf x)     = show x
  1353. > showTree (Branch l r) = "<" ++ showTree l ++ "|" ++ showTree r ++ ">"
  1354.  
  1355. > tree1 :: Tree Int
  1356. > tree1 = Branch (Leaf 1) (Branch (Leaf 3) (Leaf 6))
  1357.  
  1358. > e1 = showTree tree1
  1359.  
  1360. Now the improved showTree; shows is already defined for all
  1361. built in types.
  1362.  
  1363. > showsTree  :: Text a => Tree a -> String -> String
  1364. > showsTree (Leaf x) s = shows x s
  1365. > showsTree (Branch l r) s = '<' : showsTree l ('|' : showsTree r ('>' : s))
  1366.  
  1367. > e2 = showsTree tree1 ""
  1368.  
  1369. The final polished version.  ShowS is predefined in the Prelude so we
  1370. don't need it here. 
  1371.  
  1372. > showsTree'  :: Text a => Tree a -> ShowS
  1373. > showsTree' (Leaf x) = shows x
  1374. > showsTree' (Branch l r) = ('<' :) . showsTree' l . ('|' :) .
  1375. >                           showsTree' r . ('>' :)
  1376.  
  1377. > e3 = showsTree' tree1 ""
  1378.  
  1379.  
  1380. Page: 14    This page break is just to keep recompilation from getting too
  1381.             long.  The compiler takes a little longer to compile this
  1382.             page than other pages.
  1383.  
  1384. > module Test(Bool) where
  1385.  
  1386. > data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Text
  1387.  
  1388. Now for the reading function.  Again, ReadS is predefined and reads works
  1389. for all built-in types.  The generators in the list comprehensions are
  1390. patterns: p <- l binds pattern p to successive elements of l which
  1391. match p.  Elements not matching p are skipped.
  1392.  
  1393. > readsTree :: (Text a) => ReadS (Tree a)
  1394. > readsTree ('<':s)  = [(Branch l r, u) | (l, '|':t) <- readsTree s,
  1395. >                                         (r, '>':u) <- readsTree t ]
  1396. > readsTree s        = [(Leaf x,t)      | (x,t) <- reads s]
  1397.  
  1398. > e4 :: [(Int,String)]
  1399. > e4 = reads "5 golden rings"
  1400.  
  1401. > e5 :: [(Tree Int,String)]
  1402. > e5 = readsTree "<1|<2|3>>"
  1403. > e6 :: [(Tree Int,String)]
  1404. > e6 = readsTree "<1|2"
  1405. > e7 :: [(Tree Int,String)]
  1406. > e7 = readsTree "<1|<<2|3>|<4|5>>> junk at end"
  1407.  
  1408. Before we do the next readTree, let's play with the lex function.
  1409.  
  1410. > e8 :: [(String,String)]
  1411. > e8 = lex "foo bar bletch"
  1412.  
  1413. Here's a function to completely lex a string.  This does not handle
  1414. lexical ambiguity - lex would return more than one possible lexeme
  1415. when an ambiguity is encountered and the patterns used here would not
  1416. match.
  1417.  
  1418. > lexAll :: String -> [String]
  1419. > lexAll s = case lex s of
  1420. >             [("",_)] -> []  -- lex returns an empty token if none is found
  1421. >             [(token,rest)] -> token : lexAll rest
  1422.  
  1423. > e9 = lexAll "lexAll :: String -> [String]"
  1424. > e10 = lexAll "<1|<a|3>>"
  1425.  
  1426. Finally, the complete reader.  This is not sensitive to white space as
  1427. were the previous versions.  When you derive the Text class for a data
  1428. type the reader generated automatically is similar to this in style.
  1429.  
  1430. > readsTree' :: (Text a) => ReadS (Tree a)
  1431. > readsTree' s = [(Branch l r, x) | ("<", t) <- lex s,
  1432. >                   (l, u)   <- readsTree' t,
  1433. >                                   ("|", v) <- lex u,
  1434. >                                   (r, w)   <- readsTree' v,
  1435. >                   (">", x) <- lex w ]
  1436. >                 ++
  1437. >                 [(Leaf x, t)    | (x, t) <- reads s]
  1438.  
  1439. When testing this program, you must make sure the input conforms to
  1440. Haskell lexical syntax.  If you remove spaces between | and < or >
  1441. they will lex as a single token as you should have noticed with e10.
  1442.  
  1443. > e11 :: [(Tree Int,String)]
  1444. > e11 = readsTree' "<1 | <2 | 3> >"
  1445. > e12 :: [(Tree Bool,String)]
  1446. > e12 = readsTree' "<True|False>"
  1447.  
  1448. Finally, here is a simple version of read for trees only:
  1449.  
  1450. > read' :: (Text a) => String -> (Tree a)
  1451. > read' s = case (readsTree' s) of
  1452. >            [(tree,"")] -> tree   -- Only one parse, no junk at end
  1453. >            []          -> error "Couldn't parse tree"
  1454. >            [_]         -> error "Crud after the tree"  -- unread chars at end
  1455. >            _           -> error "Ambiguous parse of tree"
  1456.  
  1457. > e13 :: Tree Int
  1458. > e13 = read' "foo"
  1459. > e14 :: Tree Int
  1460. > e14 = read' "< 1 | < 2 | 3 > >"
  1461. > e15 :: Tree Int
  1462. > e15 = read' "3 xxx"
  1463.  
  1464. Page: 15  Section 5.4
  1465.  
  1466. > module Test(Bool) where
  1467.  
  1468. Section: 5.4  Derived Instances
  1469.  
  1470. We have actually been using the derived Text instances all along for
  1471. printing out trees and other structures we have defined.  The code
  1472. in the tutorial for the Eq and Ord instance of Tree is created
  1473. implicitly by the deriving clause so there is no need to write it
  1474. here.
  1475.  
  1476. > data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving (Eq,Ord,Text)
  1477.  
  1478. Now we can fire up both Eq and Ord functions for trees:
  1479.  
  1480. > tree1, tree2, tree3, tree4 :: Tree Int
  1481. > tree1 = Branch (Leaf 1) (Leaf 3)
  1482. > tree2 = Branch (Leaf 1) (Leaf 5)
  1483. > tree3 = Leaf 4
  1484. > tree4 = Branch (Branch (Leaf 4) (Leaf 3)) (Leaf 5)
  1485.  
  1486. > e1 = tree1 == tree1
  1487. > e2 = tree1 == tree2
  1488. > e3 = tree1 < tree2
  1489.  
  1490. > quicksort :: Ord a => [a] -> [a]
  1491. > quicksort [] = []
  1492. > quicksort (x:xs) = quicksort [y | y <- xs, y <= x] ++
  1493. >                    [x] ++
  1494. >                    quicksort [y | y <- xs, y > x]
  1495.  
  1496. > e4 = quicksort [tree1,tree2,tree3,tree4]
  1497.  
  1498. Now for Enum: 
  1499.  
  1500. > data Day = Sunday | Monday | Tuesday | Wednesday | Thursday |
  1501. >            Friday | Saturday     deriving (Text,Eq,Ord,Enum)
  1502.  
  1503. > e5 = quicksort [Monday,Saturday,Friday,Sunday]
  1504. > e6 = [Wednesday .. Friday]
  1505. > e7 = [Monday, Wednesday ..]
  1506. > e8 = [Saturday, Friday ..]
  1507.  
  1508.  
  1509. Page: 16  Sections 5.5, 5.5.1, 5.5.2, 5.5.3
  1510.  
  1511. > module Test(Bool) where
  1512.  
  1513. Section: 5.5  Numbers
  1514. Section: 5.5.1  Numeric Class Structure
  1515. Section: 5.5.2  Constructed Numbers
  1516.  
  1517. Here's a brief summary of Haskell numeric classes.
  1518.  
  1519. Class Num
  1520.   Most general numeric class.  Has addition, subtraction, multiplication.
  1521.   Integers can be coerced to any instance of Num with fromInteger.
  1522.   All integer constants are in this class.
  1523. Instances: Int, Integer, Float, Double, Ratio a, Complex a
  1524.  
  1525. Class Real
  1526.   This class contains ordered numbers which can be converted to
  1527.   rationals.
  1528. Instances: Int, Integer, Float, Double, Ratio a
  1529.  
  1530. Class Integral
  1531.   This class deals with integer division.  All values in Integral can
  1532.   be mapped onto Integer.
  1533. Instances: Int, Integer
  1534.  
  1535. Class Fractional
  1536.   These are numbers which can be divided.  Any rational number can
  1537.   be converted to a fractional.  Floating point constants are in
  1538.   this class: 1.2 would be 12/10.
  1539. Instances: Float, Double, Ratio a
  1540.  
  1541. Class Floating
  1542.   This class contains all the standard floating point functions such
  1543.   as sqrt and sin.
  1544. Instances: Float, Double, Complex a
  1545.  
  1546. Class RealFrac
  1547.   These values can be rounded to integers and approximated by rationals.
  1548. Instances: Float, Double, Ratio a
  1549.  
  1550. Class RealFloat
  1551.   These are floating point numbers constructed from a fixed precision
  1552.   mantissa and exponent.
  1553. Instances: Float, Double
  1554.  
  1555. There are only a few sensible combinations of the constructed numerics
  1556. with built-in types:
  1557.  Ratio Integer (same as Rational): arbitrary precision rationals
  1558.  Ratio Int: limited precision rationals
  1559.  Complex Float: complex numbers with standard precision components
  1560.  Complex Double: complex numbers with double precision components
  1561.  
  1562.  
  1563. The following function works for arbitrary numerics:
  1564.  
  1565. > fact :: (Num a) => a -> a
  1566. > fact 0 = 1
  1567. > fact n = n*(fact (n-1))
  1568.  
  1569. Note the behavior when applied to different types of numbers:
  1570.  
  1571. > e1 :: Int
  1572. > e1 = fact 6
  1573. > e2 :: Int
  1574. > e2 = fact 20   -- Yale Haskell may not handle overflow gracefully!
  1575. > e3 :: Integer
  1576. > e3 = fact 20
  1577. > e4 :: Rational
  1578. > e4 = fact 6
  1579. > e5 :: Float
  1580. > e5 = fact 6
  1581. > e6 :: Complex Float
  1582. > e6 = fact 6
  1583.  
  1584. Be careful: values like `fact 1.5' will loop.
  1585.  
  1586. As a practical matter, Int operations are much faster than Integer
  1587. operations.  Also, overloaded functions can be much slower than non-
  1588. overloaded functions.  Giving a function like fact a precise typing:
  1589.  
  1590. fact :: Int -> Int
  1591.  
  1592. will yield much faster code.
  1593.  
  1594. In general, numeric expressions work as expected.  Literals are
  1595. a little tricky - they are coerced to the appropriate value.  A
  1596. constant like 1 can be used as ANY numeric type.
  1597.  
  1598. > e7 :: Float
  1599. > e7 = sqrt 2
  1600. > e8 :: Rational
  1601. > e8 = ((4%5) * (1%2)) / (3%4)
  1602. > e9 :: Rational
  1603. > e9 = 2.2 * (3%11) - 1
  1604. > e10 :: Complex Float
  1605. > e10 = (2 * (3:+3)) / (1.1:+2.0 - 1)
  1606. > e11 :: Complex Float
  1607. > e11 = sqrt (-1)
  1608. > e12 :: Integer
  1609. > e12 = numerator (4%2)
  1610. > e13 :: Complex Float
  1611. > e13 = conjugate (4:+5.2)
  1612.  
  1613. A function using pattern matching on complex numbers:
  1614.  
  1615. > mag :: (RealFloat a) => Complex a -> a
  1616. > mag (a:+b) = sqrt (a^2 + b^2)
  1617.  
  1618. > e14 :: Float
  1619. > e14 = mag (1:+1)
  1620.  
  1621. Section: 5.5.3  Numeric Coercions and Overloaded Literals
  1622.  
  1623. The Haskell type system does NOT implicitly coerce values between
  1624. the different numeric types!  Although overloaded constants are 
  1625. coerced when the overloading is resolved, no implicit coercion goes
  1626. on when values of different types are mixed.  For example:
  1627.  
  1628. > f :: Float
  1629. > f = 1.1
  1630. > i1 :: Int
  1631. > i1 = 1
  1632. > i2 :: Integer
  1633. > i2 = 2
  1634.  
  1635. All of these expressions would result in a type error (try them!):
  1636.  
  1637. > -- g = i1 + f
  1638. > -- h = i1 + i2
  1639. > -- i3 :: Int
  1640. > -- i3 = i2
  1641.  
  1642. Appropriate coercions must be introduced by the user to allow
  1643. the mixing of types in arithmetic expressions.
  1644.  
  1645. > e15 :: Float
  1646. > e15 = f + fromIntegral i1
  1647. > e16 :: Integer
  1648. > e16 = fromIntegral i1 + i2
  1649. > e17 :: Int
  1650. > e17 = i1 + fromInteger i2  -- fromIntegral would have worked too.
  1651.  
  1652. Page: 17  Section 5.5.4
  1653.  
  1654. > module Test(Bool) where
  1655.  
  1656. Section: 5.5.4  Default Numeric Types
  1657.  
  1658. Ambiguous contexts arise frequently in numeric expressions.  When an
  1659. expression which produces a value with a general type, such as
  1660. `1' (same as `fromInteger 1'; the type is (Num a) => a), with
  1661. another expression which `consumes' the type, such as `show' or
  1662. `toInteger', ambiguity arises.  This ambiguity can be resolved
  1663. using expression type signatures, but this gets tedious fast!  
  1664. Assigning a type to the top level of an ambiguous expression does
  1665. not help: the ambiguity does not propagate to the top level.
  1666.  
  1667. > e1 :: String -- This type does not influence the type of the argument to show
  1668. > e1 = show 1  -- Does this mean to show an Int or a Float or ...
  1669. > e2 :: String
  1670. > e2 = show (1 :: Float)
  1671. > e3 :: String
  1672. > e3 = show (1 :: Complex Float)
  1673.  
  1674. The reason the first example works is that ambiguous numeric types are
  1675. resolved using defaults.  The defaults in effect here are Int and
  1676. Double.  Since Int `fits' in the expression for e1, Int is used.
  1677. When Int is not valid (due to other context constraints), Double
  1678. will be tried.
  1679.  
  1680. This function defaults the type of the 2's to be Int
  1681.  
  1682. > rms :: (Floating a) => a -> a -> a
  1683. > rms x y = sqrt ((x^2 + y^2) * 0.5)
  1684.  
  1685. The C-c e evaluation used to the Haskell system also makes use of
  1686. defaulting.  When you type an expression, the system creates a
  1687. simple program to print the value of the expression using a function
  1688. like show.  If no type signature for the printed expression is given,
  1689. defaulting may occur.
  1690.  
  1691. One of the reasons for adding type signatures throughout these examples
  1692. is to avoid unexpected defaulting.  Many of the top level signatures are
  1693. required to avoid ambiguity.
  1694.  
  1695. Defaulting can lead to overflow problems when values exceed Int limits.
  1696. Evaluate a very large integer without a type signature to observe this
  1697. (unfortunately this may cause a core dump or other unpleasantness).
  1698.  
  1699. Notice that defaulting applies only to numeric classes.  The
  1700.  
  1701. > --  show (read "xyz")                       -- Try this if you want!
  1702.  
  1703. example uses only class Text so no defaulting occurs.
  1704.  
  1705. Ambiguity also arises with polymorphic types.  As discussed previously,
  1706. expressions like [] have a similar problem.
  1707.  
  1708. > e4 = []   -- Won't print since [] has type [a] and `a' is not known.
  1709.  
  1710. Note the difference: even though the lists have no components, the type
  1711. of component makes a difference in printing.
  1712.  
  1713. > e5 = ([] :: [Int]) 
  1714. > e6 = ([] :: [Char])
  1715.  
  1716. Page: 18   Sections 6, 6.1, 6.2
  1717.  
  1718. Section: 6  Modules
  1719.  
  1720. > module Tree ( Tree(Leaf,Branch), fringe ) where
  1721.  
  1722. Tree(..) would work also
  1723.  
  1724. > data Tree a = Leaf a | Branch (Tree a) (Tree a)   deriving Text
  1725.  
  1726. > fringe :: Tree a -> [a]
  1727. > fringe (Leaf x)             = [x]
  1728. > fringe (Branch left right)  = fringe left ++ fringe right
  1729.  
  1730. The editor interface to Haskell performs evaluation within the
  1731. module containing the cursor.  To evaluate e1 you must place the
  1732. cursor in module Main.
  1733.  
  1734. > module Main (Tree) where
  1735. > import Tree ( Tree(Leaf, Branch), fringe)
  1736. > e1 :: [Int]
  1737. > e1 = fringe (Branch (Leaf 1) (Leaf 2))
  1738.  
  1739. You could also just `import Tree' and get everything from Tree without
  1740. explicitly naming the entities you need.
  1741.  
  1742. This interactive Haskell environment can evaluate expressions in
  1743. any module.  The use of module Main is optional.
  1744.  
  1745. Section: 6.1  Original Names and Renaming
  1746.  
  1747. > module Renamed where
  1748. > import Tree ( Tree(Leaf,Branch), fringe)
  1749. >     renaming (Leaf to Root, Branch to Twig)
  1750.  
  1751. > e2 :: Tree Int
  1752. > e2 = Twig (Root 1) (Root 2)  -- Printing always uses the original names
  1753.  
  1754. Section: 6.2  Interfaces and Implementations
  1755.  
  1756. Yale Haskell allows separate compilation of modules using
  1757. interfaces and unit files.  These are described in the user's guide.
  1758.  
  1759.  
  1760. Page: 19  Sections 6.3, 6.4
  1761.  
  1762. Section: 6.3  Abstract Data Types
  1763.  
  1764. Since TreeADT does not import Tree it can use the name Tree without
  1765. any conflict.  Each module has its own separate namespace.
  1766.  
  1767. > module TreeADT (Tree, leaf, branch, cell, left,
  1768. >                right, isLeaf) where
  1769.  
  1770. > data Tree a = Leaf a | Branch (Tree a) (Tree a)    deriving Text
  1771.  
  1772. > leaf = Leaf
  1773. > branch = Branch
  1774. > cell (Leaf a) = a
  1775. > left (Branch l r) = l
  1776. > right (Branch l r) = r
  1777. > isLeaf (Leaf _) = True
  1778. > isLeaf _        = False
  1779.  
  1780. > module Test where
  1781. > import TreeADT
  1782.  
  1783. Since the constructors for type Tree are hidden, pattern matching
  1784. cannot be used.
  1785.  
  1786. > fringe :: Tree a -> [a]
  1787. > fringe x = if isLeaf x then [cell x]
  1788. >                        else fringe (left x) ++ fringe (right x)
  1789.  
  1790. > e1 :: [Int]
  1791. > e1 = fringe (branch (branch (leaf 3) (leaf 2)) (leaf 1))
  1792.  
  1793. Section: 6.4
  1794.  
  1795. No examples are provided for 6.4.
  1796.  
  1797.  
  1798. Page: 20  Sections 7, 7.1, 7.2, 7.3
  1799.  
  1800. Section: 7  Typing Pitfalls
  1801.  
  1802. Section: 7.1  Let-Bound Polymorphism
  1803.  
  1804. > module Test(e2) where
  1805.  
  1806. > -- f g = (g 'a',g [])    -- This won't typecheck.
  1807.  
  1808. Section: 7.2  Overloaded Numerals
  1809.  
  1810. Overloaded numerics were covered previously - here is one more example.
  1811. sum is a prelude function which sums the elements of a list.
  1812.  
  1813. > average :: (Fractional a) => [a] -> a
  1814. > average xs   = sum xs / fromIntegral (length xs)
  1815.  
  1816. > e1 :: Float   -- Note that e1 would default to Double instead of Int - 
  1817. >               -- this is due to the Fractional context.
  1818. > e1 = average [1,2,3]
  1819.  
  1820. Section: 7.3  The Monomorphism Restriction
  1821.  
  1822. The monomorphism restriction is usually encountered when functions
  1823. are defined without parameters.  If you remove the signature for sum'
  1824. the monomorphism restriction will apply.
  1825. This will generate an error if either:
  1826.   sum' is added to the module export list at the start of this section
  1827.   both sumInt and sumFloat remain in the program.
  1828. If sum' is not exported and all uses of sum' have the same overloading,
  1829. there is no type error.
  1830.  
  1831. > sum' :: (Num a) => [a] -> a
  1832. > sum' = foldl (+) 0         -- foldl reduces a list with a binary function
  1833. >                            -- 0 is the initial value.
  1834.  
  1835. > sumInt :: Int
  1836. > sumInt = sum' [1,2,3]
  1837.  
  1838. > sumFloat :: Float
  1839. > sumFloat = sum' [1,2,3]
  1840.  
  1841. If you use overloaded constants you also may encounter monomorphism:
  1842.  
  1843. > x :: Num a => a
  1844. > x = 1    -- The type of x is Num a => a
  1845. > y :: Int
  1846. > y = x            -- Uses x as an Int
  1847. > z :: Integer
  1848. > z = x          -- Uses x as an Integer.  A monomorphism will occur of the
  1849. >                -- signature for x is removed.
  1850.  
  1851. The error message that this generates is somewhat arbitrary.  When the
  1852. monomorphism restriction applies, the first use of x will determine
  1853. the type and the second will cause the type error.  There is no way to
  1854. be sure which use of x the type checker will encounter first; either
  1855. the `y = x' or the `z = x' may be flagged as the place where the error
  1856. occurs depending on the order in which type checking scans the program.
  1857.  
  1858. Finally, if a value is exported it must not be overloaded unless bound
  1859. by a function binding.  e2 is the only value exported.
  1860.  
  1861. > e2 :: Int  -- Remove this to get an error.  Without this line e1 will
  1862. >            -- be overloaded.
  1863. > e2 = 1
  1864.  
  1865. To prevent annoying error messages about exported monomorphic variables,
  1866. most modules in this tutorial do not implicitly export everything - they
  1867. only export a single value, Bool, which was chosen to keep the export
  1868. list non-empty (a syntactic restriction!).  In Haskell systems without
  1869. the evaluator used here, a module which does not export any names would
  1870. be useless.
  1871.  
  1872. module Test where  -- this would export everything in the module
  1873. module Test(Bool)  -- exports only Bool
  1874. module Test()      -- this is what we really want to do but is not valid.
  1875.  
  1876. Page: 21  Sections 8, 8.1
  1877.  
  1878. > module Test(Bool) where
  1879.  
  1880. Section: 8  Input/Output
  1881. Section: 8.1  Introduction to Continuations
  1882.  
  1883. Simplify f here to be 1/x.
  1884.  
  1885. > data Possibly a  = Ok a | Oops String deriving Text
  1886.  
  1887. > f :: Float -> Possibly Float
  1888. > f x = if x == 0 then Oops "Divide by 0" else Ok (1/x)
  1889.  
  1890. g is a `safe' call to x.  The call to error could be replaced by
  1891. some explicit value like Oops msg -> 0.
  1892.  
  1893. > g x = case f x of
  1894. >         Ok y -> y
  1895. >         Oops msg -> error msg
  1896.    
  1897. > e1 = f 0
  1898. > e2 = g 0
  1899. > e3 = g 1
  1900.  
  1901. Here is the same example using continuations:
  1902.  
  1903. > f' :: Float -> (String -> Float) -> Float
  1904. > f' x c = if x == 0 then c "Divide by 0"
  1905. >                    else 1/x
  1906.  
  1907. > g' x = f' x error   -- calls error on divide by 0
  1908. > g'' x = f' x (\s -> 0) -- returns 0 on divide by 0
  1909.  
  1910. > e4 = g' 0
  1911. > e5 = g'' 0
  1912.  
  1913. Page: 22  Section 8
  1914.  
  1915. > module Test where
  1916.  
  1917. > import Prelude hiding (putStr, getLine)
  1918.  
  1919. Section: 8.1  The I/O Monad
  1920.  
  1921. The I/O monad divides the Haskell world into values and actions.  So far,
  1922. we have only needed to look at values.  To deal with actions, we need
  1923. to introduce a new editor command: C-c r.  We use the term `dialogue'
  1924. to denote an action returning no value, as indicated by the type `IO ()'.
  1925. Instead of printing a value, C-c r runs a dialogue.  (Actually C-c e creates
  1926. an action on the fly and runs it in the same manner as C-c r).  
  1927. As with C-c e you are prompted for an expression; here the type of the
  1928. expression must be IO ().  We use d1,d2,... for dialogues to be
  1929. executed by C-c r.
  1930.  
  1931. In an interactive environment such as this, there is no real need to
  1932. use `main' in module `Main' to designate the dialogue associated with a
  1933. program since C-c r queries for the dialogue to be executed.
  1934. However, many commands such as C-c m make use of this convention.
  1935.  
  1936. The first example is putStr:
  1937.  
  1938. > putStr    :: String -> IO ()
  1939. > putStr s = foldr (>>) (return ()) (map putChar s)
  1940.  
  1941. > d1 = putStr "Hello World"
  1942.  
  1943. Both putStr and getLine are actually in the prelude.
  1944.  
  1945. > getLine :: IO String
  1946. > getLine = getChar >>= (\c ->
  1947. >           if c == '\n' then return ""
  1948. >                        else getLine >>= (\l -> return (c:l)))
  1949.  
  1950. > d2 = putStr "Type Something: " >> getLine >>= (\str ->
  1951. >      putStr "You typed: " >> putStr str >> putStr "\n")
  1952.  
  1953. To experiment with I/O errors, we need to get a bit creative.  Generating
  1954. an error is generally OS specific so instead we use a new
  1955. version of getLine that raises an error when a blank line is entered:
  1956.  
  1957. > getLineErr = getLine >>= (\l ->
  1958. >              if l == "" then failwith EOF
  1959. >                         else return l)
  1960.  
  1961. First, enter a blank line with no active error handler: 
  1962.  
  1963. > d3 = getLineErr >>= putStr
  1964.  
  1965. Now with an error handler:
  1966.  
  1967. > d4 = try getLineErr (\ e -> return (show e)) >>= putStr
  1968.  
  1969. This is the file copier:
  1970.  
  1971. > d5 = getAndOpenFile "Copy from: " ReadMode >>= (\fromHandle ->
  1972. >      getAndOpenFile "Copy to: " WriteMode >>= (\toHandle ->
  1973. >      getContents fromHandle >>= (\contents ->
  1974. >      hPutStr toHandle contents >> close toHandle >> putStr "Done.\n")))
  1975.  
  1976. > getAndOpenFile :: String -> IOMode -> IO Handle
  1977.  
  1978. > getAndOpenFile prompt mode =
  1979. >     putStr prompt >>
  1980. >     getLine >>= (\name ->
  1981. >     try (openFile mode name)
  1982. >         (\err -> putStr ("Cannot open "++ name ++ "\n") >>
  1983. >                  getAndOpenFile prompt mode))
  1984.  
  1985. Finally, an example not in the tutorial.  Reading stdin using getContents
  1986. makes the demands for evaluation of the input stream visible to the user
  1987. since the program will stop for input whenever demand reaches a new line in
  1988. the input stream.
  1989.  
  1990. This reads the entire input stream, breaks it into lines, and hands a list
  1991. of lines to munchInput:
  1992.  
  1993. > d6 = getContents stdin >>= \i -> munchInput (lines i)
  1994.  
  1995. The munchInput function looks at the next line of input.  It prints a prompt
  1996. and then looks at a line of input.  The command `stop' halts execution,
  1997. the command `skip' skips over the next input line, and anything else is
  1998. echoed.
  1999.  
  2000. > munchInput (l:ls) =
  2001. >   putStr "* " >>
  2002. >   case l of
  2003. >    "stop" -> return ()
  2004. >    "skip" -> munchInput (tail ls)
  2005. >    _      -> putStr (l ++ " not understood.\n") >> munchInput ls
  2006.  
  2007. Run this program.  There is a problem with the prompting: it reads the
  2008. input line before the prompt is printed out.  While the case statement would
  2009. be expected to demand a line of input, this demand actually occurs earlier.
  2010. The pattern (l:ls) can only be matched by stripping a line of the input
  2011. stream.  Since this pattern is matched upon entry to munchInput, the input
  2012. demand occurs before the prompt can be printed.
  2013.  
  2014. Change the first line of munchInput to:
  2015.  
  2016. munchInput ~(l:ls) =
  2017.  
  2018. This will allow the prompt to print out before the case statement looks at
  2019. the value of l.  Run the program again.
  2020.  
  2021. Note the behavior when you type "skip".  Again, you need to understand when
  2022. the input will be demanded to figure out why the prompt prints before the
  2023. ignored input line.  Now change this by putting a something in the
  2024. recursive call to munchInput which will look at the line being discarded
  2025. before the recursive call:
  2026.  
  2027.   "skip" -> case ls of (_ : t) -> munchInput t
  2028.  
  2029. This reads the skipped line before the prompt on the recursive call.
  2030.  
  2031. If you find all of this confusing, then the lesson here is that it is probably
  2032. best to avoid reading stdin with getContents.  Using getLine to read a line
  2033. at a time is much easier to understand.  Since getLine is strict with respect
  2034. to the input, there is no way that later demands will suddenly stop execution
  2035. to wait for input.
  2036.  
  2037. For more examples using the I/O system look in the demo programs
  2038. that come with haskell (in $HASKELL/progs/demo) and the report.
  2039.  
  2040. Page: 23  Sections 9, 9.1, 9.2
  2041.  
  2042. > module Test(Bool) where
  2043.  
  2044. Section: 9  Arrays
  2045. Section: 9.1  Index Types
  2046.  
  2047. Arrays are built on the class Ix.  Here are some quick examples of Ix:
  2048.  
  2049. > e1 :: [Int]
  2050. > e1 = range (0,4)
  2051. > e2 :: Int
  2052. > e2 = index (0,4) 2
  2053. > low,high :: (Int,Int)
  2054. > low = (1,1)
  2055. > high = (3,4)
  2056. > e3 = range (low,high)
  2057. > e4 = index (low,high) (3,2)
  2058. > e5 = inRange (low,high) (4,3)
  2059.  
  2060. Section: 9.2  Array Creation
  2061.  
  2062. > squares :: Array Int Int
  2063. > squares = array (1,100) [(i,i*i) | i <- [1..100]]
  2064.  
  2065. We can also parameterize this a little:
  2066.  
  2067. > squares' :: Int -> Array Int Int
  2068. > squares' n = array (1,n) [(i,i*i) | i <- [1..n]]
  2069.  
  2070. > e6 :: Int
  2071. > e6 = squares!6
  2072. > e7 :: (Int,Int)
  2073. > e7 = bounds squares
  2074. > e8 :: Array Int Int
  2075. > e8 = squares' 10
  2076.  
  2077. Here is a function which corresponds to `take' for lists.  It takes
  2078. an arbitrary slice out of an array.
  2079.  
  2080. > atake :: (Ix a) => Array a b -> (a,a) -> Array a b
  2081. > atake a (l,u) | inRange (bounds a) l && inRange (bounds a) u =
  2082. >                    array (l,u) [(i,a!i) | i <- range (l,u)]
  2083. >               | otherwise = error "Subarray out of range"
  2084.  
  2085. > e9 = atake squares (4,8)
  2086.  
  2087. > mkArray :: Ix a => (a -> b) -> (a,a) -> Array a b
  2088. > mkArray f bnds = array bnds [(i,f i) | i <- range bnds]
  2089.  
  2090. > e10 :: Array Int Int
  2091. > e10 = mkArray (\i -> i*i) (1,10)
  2092.  
  2093. > fibs :: Int -> Array Int Int
  2094. > fibs n = a where
  2095. >             a = array (0,n) ([(0,1), (1,1)] ++
  2096. >                              [(i,a!(i-1) + a!(i-2)) | i <- [2..n]])
  2097.  
  2098. > e11 = atake (fibs 50) (3,10)
  2099.  
  2100. > wavefront :: Int -> Array (Int,Int) Int
  2101. > wavefront n = a where
  2102. >                 a = array ((1,1),(n,n))
  2103. >                      ([((1,j),1) | j <- [1..n]] ++
  2104. >                       [((i,1),1) | i <- [2..n]] ++
  2105. >                       [((i,j),a!(i,j-1) + a!(i-1,j-1) + a!(i-1,j))
  2106. >                                   | i <- [2..n], j <- [2..n]])
  2107.  
  2108. > wave = wavefront 20
  2109. > e12 = atake wave ((1,1),(3,3))
  2110. > e13 = atake wave ((3,3),(5,5))
  2111.  
  2112. Here are some errors in array operations:
  2113.  
  2114. > e14 :: Int
  2115. > e14 = wave ! (0,0)  -- Out of bounds
  2116. > arr1 :: Array Int Int
  2117. > arr1 = array (1,10) [(1,1)] -- No value provided for 2..10
  2118. > e15,e16 :: Int
  2119. > e15 = arr1 ! 1  -- works OK
  2120. > e16 = arr1 ! 2  -- undefined by array
  2121.  
  2122. Page: 24  Sections 9.3, 9.4
  2123.  
  2124. > module Test(Bool) where
  2125.  
  2126. Section: 9.3  Accumulation
  2127.  
  2128. > hist :: (Ix a, Integral b) => (a,a) -> [a] -> Array a b
  2129. > hist bnds is = accumArray (+) 0 bnds [(i,1) | i <- is, inRange bnds i]
  2130.  
  2131. > e1 :: Array Char Int
  2132. > e1 = hist ('a','z') "This counts the frequencies of each lowercase letter"
  2133.  
  2134. > decades :: (RealFrac a) => a -> a -> [a] -> Array Int Int
  2135. > decades a b = hist (0,9) . map decade
  2136. >                 where
  2137. >                   decade x = floor ((x-a) * s)
  2138. >                   s = 10 / (b - a)
  2139.  
  2140. > test1 :: [Float]
  2141. > test1 = map sin [0..100]  -- take the sine of the 0 - 100
  2142. > e2 = decades 0 1 test1
  2143.  
  2144. Section: 9.4  Incremental Updates
  2145.  
  2146. > swapRows :: (Ix a, Ix b, Enum b) => a -> a -> Array (a,b) c -> Array (a,b) c
  2147. > swapRows i i' a = a // ([((i,j),a!(i',j)) | j <- [jLo..jHi]] ++
  2148. >               [((i',j),a!(i,j)) | j <- [jLo..jHi]])
  2149. >                where ((iLo,jLo),(iHi,jHi)) = bounds a
  2150.  
  2151. > arr1 :: Array (Int,Int) (Int,Int)
  2152. > arr1 = array ((1,1),(5,5)) [((i,j),(i,j)) | (i,j) <- range ((1,1),(5,5))]
  2153.  
  2154. > e3 = swapRows 2 3 arr1
  2155.  
  2156. Printing the arrays in more readable form makes the results easier
  2157. to view.
  2158.  
  2159. This is a printer for 2d arrays
  2160.  
  2161. > aprint a width = shows (bounds a) . showChar '\n' . showRows lx ly where
  2162. >   showRows r c | r > ux = showChar '\n'
  2163. >   showRows r c | c > uy = showChar '\n' . showRows (r+1) ly
  2164. >   showRows r c = showElt (a!(r,c)) . showRows r (c+1)
  2165. >   showElt e = showString (take width (show e ++ repeat ' ')) . showChar ' '
  2166. >   ((lx,ly),(ux,uy)) = bounds a
  2167.  
  2168. > showArray a w = appendChan stdout (aprint a w "") abort done
  2169.  
  2170. > d1 = showArray e3 6
  2171.  
  2172. > swapRows' :: (Ix a, Ix b, Enum b) => a -> a -> Array (a,b) c -> Array (a,b) c
  2173. > swapRows' i i' a = a // [assoc | j <- [jLo..jHi],
  2174. >                                  assoc <- [((i,j),a!(i',j)),
  2175. >                            ((i',j),a!(i,j))]]
  2176. >                where ((iLo,jLo),(iHi,jHi)) = bounds a
  2177.  
  2178. > d2 = showArray (swapRows' 1 5 arr1) 6
  2179.  
  2180. Page: 25  Section 9.5
  2181.  
  2182. > module Test(Bool) where
  2183.  
  2184. Section: 9.5  An example: Matrix Multiplication
  2185.  
  2186. > aprint a width = shows (bounds a) . showChar '\n' . showRows lx ly where
  2187. >   showRows r c | r > ux = showChar '\n'
  2188. >   showRows r c | c > uy = showChar '\n' . showRows (r+1) ly
  2189. >   showRows r c = showElt (a!(r,c)) . showRows r (c+1)
  2190. >   showElt e = showString (take width (show e ++ repeat ' ')) . showChar ' '
  2191. >   ((lx,ly),(ux,uy)) = bounds a
  2192.  
  2193. > showArray a w = appendChan stdout (aprint a w "") abort done
  2194.  
  2195. > matMult :: (Ix a, Ix b, Ix c, Num d) =>
  2196. >               Array (a,b) d -> Array (b,c) d -> Array (a,c) d
  2197. > matMult x y =
  2198. >   array resultBounds
  2199. >         [((i,j), sum [x!(i,k) * y!(k,j) | k <- range (lj,uj)])
  2200. >                   | i <- range (li,ui),
  2201. >                     j <- range (lj',uj')]
  2202. >  where
  2203. >     ((li,lj),(ui,uj)) = bounds x
  2204. >     ((li',lj'),(ui',uj')) = bounds y
  2205. >     resultBounds
  2206. >       | (lj,uj)==(li',ui')    =  ((li,lj'),(ui,uj'))
  2207. >       | otherwise             = error "matMult: incompatible bounds"
  2208.  
  2209. > mat1,mat2,mat3,mat4 :: Array (Int,Int) Int
  2210. > mat1 = array ((0,0),(1,1)) [((0,0),1), ((0,1),0), ((1,0),0), ((1,1),1)] 
  2211. > mat2 = array ((0,0),(1,1)) [((0,0),1), ((0,1),1), ((1,0),1), ((1,1),1)] 
  2212. > mat3 = array ((0,0),(1,1)) [((0,0),1), ((0,1),2), ((1,0),3), ((1,1),4)] 
  2213. > mat4 = array ((0,0),(1,2)) [((0,0),1), ((0,1),2), ((0,2),3), 
  2214. >                   ((1,0),4), ((1,1),5), ((1,2),6)] 
  2215.  
  2216. > d1 = showArray (matMult mat1 mat2) 4
  2217. > d2 = showArray (matMult mat2 mat3) 4
  2218. > d3 = showArray (matMult mat1 mat4) 4
  2219. > d4 = showArray (matMult mat4 mat1) 4
  2220.  
  2221. > matMult' :: (Ix a, Ix b, Ix c, Num d) =>
  2222. >               Array (a,b) d -> Array (b,c) d -> Array (a,c) d
  2223. > matMult' x y =
  2224. >   accumArray (+) 0 ((li,lj'),(ui,uj'))
  2225. >         [((i,j), x!(i,k) * y!(k,j))
  2226. >                   | i <- range (li,ui),
  2227. >                     j <- range (lj',uj'),
  2228. >                     k <- range (lj,uj)]
  2229. >  where
  2230. >     ((li,lj),(ui,uj)) = bounds x
  2231. >     ((li',lj'),(ui',uj')) = bounds y
  2232. >     resultBounds
  2233. >        | (lj,uj)==(li',ui')    =  ((li,lj'),(ui,uj'))
  2234. >        | otherwise             = error "matMult: incompatible bounds"
  2235.  
  2236. > d5 = showArray (matMult mat1 mat2) 4
  2237. > d6 = showArray (matMult mat2 mat3) 4
  2238.  
  2239. > genMatMul :: (Ix a, Ix b, Ix c) =>
  2240. >               ([f] -> g) -> (d -> e -> f) ->
  2241. >               Array (a,b) d -> Array (b,c) e -> Array (a,c) g
  2242. > genMatMul f g x y =
  2243. >   array ((li,lj'),(ui,uj'))
  2244. >         [((i,j), f [(x!(i,k)) `g` (y!(k,j)) | k <- range (lj,uj)])
  2245. >                   | i <- range (li,ui),
  2246. >                     j <- range (lj',uj')]
  2247. >  where
  2248. >     ((li,lj),(ui,uj)) = bounds x
  2249. >     ((li',lj'),(ui',uj')) = bounds y
  2250. >     resultBounds
  2251. >          | (lj,uj)==(li',ui')    =  ((li,lj'),(ui,uj'))
  2252. >          | otherwise             = error "matMult: incompatible bounds"
  2253.  
  2254. > d7 = showArray (genMatMul maximum (-) mat2 mat1) 4
  2255. > d8 = showArray (genMatMul and (==) mat1 mat2) 6
  2256. > d9 = showArray (genMatMul and (==) mat1 mat1) 6
  2257.  
  2258. Page: 26     More about Haskell
  2259.  
  2260. This is the end of the tutorial on official Haskell.  If you wish to
  2261. see more examples of Haskell programming, Yale Haskell comes with a
  2262. set of demo programs. These can be found in $HASKELL/progs/demo.  Once
  2263. you have mastered the tutorial, both the report and the user manual
  2264. for Yale Haskell should be understandable.  Many examples of Haskell
  2265. programming can be found in the Prelude.  The directory
  2266. $HASKELL/progs/prelude contains the sources for the Prelude.
  2267.  
  2268. The following pages describe extensions which have been added to the
  2269. Yale system and are not officially a part of the Haskell language.
  2270. Proceed at your own risk!
  2271.  
  2272. We appreciate any comments you have on this tutorial.  Send any comments
  2273. to haskell-requests@cs.yale.edu.
  2274.  
  2275.    The Yale Haskell Group
  2276.  
  2277. Page: 27    Basic Dynamic Typing
  2278.  
  2279. > module Foo(Bool) where
  2280.  
  2281. > import Dynamic
  2282.  
  2283. The next few pages present an overview of the Yale dynamic typing system.
  2284. A tech report describing this approach to dynamic typing is distributed
  2285. in the $HASKELL/doc/dynamic directory.  The prelude files
  2286.  $PRELUDE/PreludeDynamic.hs
  2287.  $PRELUDE/PreludeDeriving.hs
  2288. have quite a bit of documentation in them also.
  2289.  
  2290. Any module using dynamic typing must import Dynamic
  2291.  
  2292. A value of any type can be converted to a single type, Dynamic, using
  2293. the 'toDynamic' construct:
  2294.  
  2295. > e1 = toDynamic True
  2296.  
  2297. > e2 = toDynamic ("abc",False,'z')
  2298.  
  2299. While it uses function calling syntax, toDynamic is not a function
  2300. but a special construct.  Thus `map toDynamic l' would be meaningless.
  2301.  
  2302. When printed, only the signature of the dynamic value is shown.  The
  2303. value inside the dynamic is not printed.
  2304.  
  2305. Dynamic values may be overloaded:
  2306.  
  2307. > e3 = toDynamic 1  -- remember that Haskell adds an implicit 'fromInteger' here
  2308.  
  2309. > e4 = toDynamic (+)
  2310.  
  2311. The inverse of toDynamic is fromDynamic.  This integrates a dynamic
  2312. into the existing type context.
  2313.  
  2314. This function requires that the result of fromDynamic is an Int:
  2315.  
  2316. > f :: Dynamic -> Int
  2317. > f x = fromDynamic x + 1
  2318.  
  2319. > e5 = f (toDynamic 2)
  2320.  
  2321. fromDynamic will fail at runtime if the type of the dynamic is not
  2322. appropriate.  The dynamic type may be more general than the desired
  2323. type (as in e5, since the type of 2 is Num a => a)
  2324.  
  2325. > e6 = f (toDynamic False)  -- This will fail at run time.
  2326.  
  2327. To interrogate the type of a dynamic value, pattern matching can be
  2328. used.  The pattern (p :: Signature) matches a dynamic whose type is
  2329. type is the same as (or can be coereced to) the signature.
  2330.  
  2331. > t (x :: Bool) = if x then "True" else "False"
  2332. > t (x :: Int) = "Int"
  2333. > t (x :: Integer) = "Integer"
  2334. > t _ = "Something else"
  2335.  
  2336. > e7 = t (toDynamic True)
  2337. > e8 = t (toDynamic (1 :: Integer))
  2338. > e9 = t (toDynamic 1)  -- This could match Int or Integer
  2339.  
  2340. More general patterns are also useful:
  2341.  
  2342. > sh (x :: Text a => a) = show x
  2343. > sh _ = "<<Error>>"
  2344.  
  2345. > e10 = sh e1
  2346. > e11 = sh e2
  2347.  
  2348. > data NotInText = NotInText
  2349.  
  2350. > e12 = sh (toDynamic NotInText)
  2351.  
  2352. To round off the special dynamic type operators available, 'typeOf' is
  2353. provided to compute the type of an object.  This returns the 'Signature'
  2354. type which is defined in the module Dynamic.
  2355.  
  2356. > e13 = typeOf foldr
  2357.  
  2358. > e14 = typeOf ((+),"abc",1)
  2359.  
  2360.  
  2361. Page: 28   Operating in the Dynamic domain
  2362.  
  2363. > module Foo(Bool) where
  2364.  
  2365. > import DynamicInternal
  2366.  
  2367. Many operations are supplied for the values and types used by the
  2368. dynamic typing system.
  2369.  
  2370. > dyn1 = toDynamic (1 :: Int)
  2371. > dyn2 = toDynamic "abc"
  2372. > dyn3 = toDynamic (+)
  2373. > dyn4 = toDynamic (error "Evaluating dyn4" :: String)
  2374. > dyn5 = toDynamic (error "Evaluating dyn5")
  2375.  
  2376. The type of a dynamic can be obtained by dType:
  2377. dType :: Dynamic -> Signature
  2378.  
  2379. > e1 = dType dyn1
  2380. > e2 = dType dyn3
  2381.  
  2382. The top level datatype is returned by dDataType:
  2383. dDataType :: Dynamic -> DataType
  2384.  
  2385. > e3 = dDataType dyn1
  2386. > e4 = dDataType dyn2
  2387. > e5 = dDataType dyn4
  2388. > e6 = dDataType dyn5  -- This value has no data type
  2389.  
  2390. Note: the Haskell committee has decided on some official names for
  2391. unnamed types, such as (->) for the function type, [] for the list
  2392. type, and (,) for tuple types.  The dynamic types for these constructs
  2393. do not yet have these names.
  2394.  
  2395. dConstructor returns the data constructor which
  2396. created the value.  This evaluates the data value.
  2397.  
  2398. > e7 = dConstructor dyn1 -- Numerics have a bogus internal constructor
  2399. > e8 = dConstructor dyn2 
  2400. > e9 = dConstructor dyn3 -- Internal constructor for functions
  2401. > e10 = dConstructor dyn4
  2402.  
  2403. The dSlots function take apart a dynamic value:
  2404.  
  2405. > e11 = dSlots dyn2  -- This would be meaningless for the other dynamics
  2406.  
  2407. Finally, dShow converts a dynamic to a string.  This is possible
  2408. even when Text instances are not available for the type.
  2409.  
  2410. > e12 = dShow dyn1
  2411. > e13 = dShow dyn2
  2412. > e14 = map dShow e11
  2413.  
  2414. Function application in the dynamic domain is performed by dApply:
  2415.  dApply :: Dynamic -> [Dynamic] -> Dynamic
  2416.  
  2417. > e15 = dShow (dApply dyn3 [dyn1,dyn1])
  2418. > e16 = dShow (dApply dyn3 [dyn2]) -- A special dynamic type is used for errors.
  2419.  
  2420. Many more dynamic operations are available - see accompanying documentation.
  2421.  
  2422. Page: 29   Existential Types and Dynamic Typing
  2423.  
  2424. > module Foo(Bool) where
  2425.  
  2426. > import Dynamic
  2427.  
  2428. When polymorphism is present, dynamic typing cannot completely capture
  2429. the type of a object.
  2430.  
  2431. > f :: a -> Dynamic
  2432. > f x = toDynamic x
  2433.  
  2434. This function does not have any information about the type of its argument.
  2435. What happens is that a new type is created at runtime every time f is
  2436. called.  These types are called skolem types.
  2437.  
  2438. > e1 = f True
  2439.  
  2440. > e2 = f "abc"
  2441.  
  2442. The type captured by f is basicly useless since this type has no
  2443. 'interesting' properties.  A much more useful function would be
  2444.  
  2445. > f1 :: Num a => a -> Dynamic
  2446. > f1 x = toDynamic x
  2447.  
  2448. > e3 = f1 (1 :: Int)
  2449.  
  2450. The skolem type introduced by f1 will be an instance of Num.
  2451. The signature on f1 is necessary - without it this would have been
  2452. the same as f.
  2453.  
  2454. The following function can be applied to any numeric type, including
  2455. the skolem type found in e3.
  2456.  
  2457. > f2 (x :: Num a => a) = toDynamic (x+2)
  2458.  
  2459. > e4 = f2 e3
  2460.  
  2461. Note that the type in e4 is the same as the type in e3.  Unfortunately
  2462. there is no way to recover the original type, Int.  However, the value
  2463. can be obtained through 'show':
  2464.  
  2465. > e5 = case e4 of (x :: Text a => a) -> show x
  2466.  
  2467. This works because Text is a superclass of Num.
  2468.  
  2469. Warning: skolemization is impure!  Any program that 'looks at' a
  2470. skolem type the wrong way will lose referential transparency.  While
  2471. it is very convenient to have skolem types, they should be used with great
  2472. care.
  2473.  
  2474. More examples of type skolemization can be found in the documentation
  2475. of the dynamic typing system but no further examples will be given here.
  2476.  
  2477. Page: 30    Generalizing Derived Instances with Dynamics
  2478.  
  2479. > module Foo(Bool) where
  2480.  
  2481. > import Dynamic
  2482.  
  2483. One important application of dynamic typing is a generalization of
  2484. derived instances.  In the Haskell report, the various derived instances
  2485. are specified using code templates which are based on datatype 
  2486. declarations. 
  2487. No formal mechanism is provided to add new code templates to Haskell -
  2488. there is no way to add a new derivable instance to the language.
  2489.  
  2490. The Yale compiler provides a mechanism which allows the user to
  2491. introduce new derived instances.  The declaration:
  2492.  
  2493. deriving DI t where
  2494.  instance C t where
  2495.    decl1
  2496.    decl2
  2497.  
  2498. defines a new derived instance, DI, which is expanded by creating an
  2499. instance declaration containing the given decls.  For example, you
  2500. could define a class:
  2501.  
  2502. > class NamedType a where
  2503. >   typeName :: a -> String
  2504.  
  2505. > deriving NamedType a where
  2506. >   instance NamedType a where
  2507. >     typeName x = dDataTypeName (dDataType (toDynamic x))
  2508.  
  2509. > data T1 = T1 deriving NamedType
  2510.  
  2511. > data T2 = T2 deriving NamedType
  2512.  
  2513. > e1 = typeName T1
  2514. > e2 = typeName T2
  2515.  
  2516. All of the standard derived instances propagate their context down to
  2517. the components of a datatype.  For example, for a type to be an instance
  2518. of Eq, all components must also be an instance of Eq.  
  2519.  
  2520. This is a new version of Eq:
  2521.  
  2522. > class MyEq a where
  2523. >   eq :: a -> a -> Bool
  2524.  
  2525. This deriving declaration creates a new derived instance, MyEq, and
  2526. uses dynamic typing to perform the computation of eq.  The context in
  2527. the class declaration, MyEq t, is not applied to the type t but to all
  2528. component types in t.  It may have been cleaner to use something like
  2529.   instance MyEq (subTypes t) => MyEq t
  2530. but this would add extra syntax to the language.
  2531.  
  2532. > deriving MyEq t where
  2533. >   instance MyEq t => MyEq t where
  2534. >     eq x y = dynamicEq (toDynamic x) (toDynamic y)
  2535.  
  2536. This dynamicEq function has different strictness properties from the
  2537. standard Eq class.  It compares right to left instead of left to right.
  2538.  
  2539. > dynamicEq x y = tag x == tag y && foldr (flip (&&)) True slotEqs where
  2540. >   tag x = dConstructorTag (dConstructor x)
  2541. >   slotEqs = zipWith dynEq (dSlots x) (dSlots y)
  2542. >   dynEq x (y :: MyEq a => a) = eq (fromDynamic x) y
  2543.  
  2544. > data Foo = C1 Foo Foo | C2 deriving (Eq,MyEq,Text)
  2545.  
  2546. > e3 = (C1 C2 (C1 C2 C2)) `eq` (C1 C2 (C1 C2 C2))
  2547.  
  2548. > e4 = (C1 C2 (C1 C2 C2)) == (C1 C2 (C1 C2 C2))
  2549.  
  2550. > e5 = (C1 C2 (error "2nd slot")) `eq` (C1 (C1 C2 C2) C2)
  2551.  
  2552. > e6 = (C1 C2 (error "2nd slot")) == (C1 (C1 C2 C2) C2)
  2553.  
  2554. > e7 = (C1 (error "1st slot") C2) `eq` (C1 C2 (C1 C2 C2))
  2555.  
  2556. > e8 = (C1 (error "1st slot") C2) == (C1 C2 (C1 C2 C2))
  2557.  
  2558. The class does not need to match the name of the derived instance.
  2559. For example, an alternative Text instance could be supplied:
  2560.  
  2561. > deriving Text' t where
  2562. >   instance Text t where
  2563. >     showsPrec p x = showDyn (toDynamic x)
  2564.  
  2565. > showDyn x = showString "<<" .
  2566. >             showString (dDataTypeName (dDataType x)) .
  2567. >             showString ">>"
  2568.  
  2569. > data A = B | C deriving Text'
  2570.  
  2571. > e9 = (B,True,[C,B])
  2572.  
  2573. Some other features:
  2574.  
  2575. More than one instance declaration can be supplied in a deriving 
  2576. declaration.
  2577.  
  2578. A context in the deriving declaration can be used to require the presence
  2579. of other instances for the type:
  2580.  
  2581. deriving Eq t => Bar t where
  2582.    instance Ord t where ...
  2583.    
  2584. This deriving will fail if no Eq instance is supplied for the type t.
  2585.  
  2586. The data type can be restricted to enumerated or tuple data types.
  2587. Look into PreludeDeriving for more examples of the deriving declaration.
  2588.  
  2589. This is the end of the tutorial.
  2590.